JavaScript/Bookmarklets

维基教科书,自由的教学读本

Bookmarklet是存储在书签的URL字段中的一行脚本。书签已经存在了很长时间,因此它们可以在较旧的浏览器中使用。

JavaScript URI 方案[编辑]

您应该熟悉以httpftp等方案开头的 URL ,例如http://en.wikibooks.org/。还有用于启动每个书签的JavaScript方案。

JavaScript:alert('Hello, World!');

示例使用[编辑]

媒体控制[编辑]

The values in these examples can be adapted as desired. One may replace video with audio where applicable, meaning where an <audio> tag is embedded. 这些示例中的值可以根据需要进行调整。在适用的情况下,video可以替换为audio,意味着一个audio标签被嵌入。

循环播放视频
javascript:document.getElementsByTagName("video")[0].loop=1;
javascript:document.getElementsByTagName("video")[0].loop=true; // also works

可以使用0false关闭。

跳到十分钟(使用乘法)
javascript:document.getElementsByTagName("video")[0].currentTime=60*10;
向前跳一分钟(六十秒)
javascript:document.getElementsByTagName("video")[0].currentTime+=60;
向后跳半分钟(使用除法)
javascript:document.getElementsByTagName("video")[0].currentTime-=60/2;
获取控制台页面上视频的持续时间
javascript:document.getElementsByTagName("video")[0].duration
提醒持续时间
javascript:alert('This video is '+document.getElementsByTagName("video")[0].duration+' seconds long.')
提醒播放时间
javascript:alert('The current position of the video is at '+document.getElementsByTagName("video")[0].currentTime+' seconds.')
将音量设置为 50%
javascript:document.getElementsByTagName("video")[0].volume=50/100
静音
javascript:document.getElementsByTagName("video")[0].muted=1 // "true" works as well

Unmute using 0 or false.

播放速度翻倍
javascript:document.getElementsByTagName("video")[0].playbackRate=2
询问播放速度
javascript:document.getElementsByTagName("video")[0].playbackRate= parseFloat( prompt("How fast should it play?") );

parseFloat如果对话窗口在没有用户输入的情况下关闭,则必须防止将值设置为零。

以秒为单位询问播放位置
javascript:document.getElementsByTagName("video")[0].currentTime=parseFloat( prompt("Jump to playback position in seconds:") );
以分钟为单位询问播放位置
javascript:document.getElementsByTagName("video")[0].currentTime=60*parseFloat( prompt("Jump to playback position in minutes:") );
以百分比请求播放位置(0 到 100)
javascript:document.getElementsByTagName("video")[0].currentTime=document.getElementsByTagName("video")[0].duration/100*parseFloat( prompt("Jump to playback position in percents:") );

使用多行代码[编辑]

由于您不能在书签中使用换行符,因此您必须在每个代码语句的末尾使用分号。

JavaScript:name=prompt('What is your name?'); alert('Hello, ' + name);

链接中的JavaScript协议[编辑]

JavaScript协议可用于链接。这可能被认为是不好的做法,因为它会阻止禁用 JavaScript 的用户访问或混淆。请参阅Best Practices

<a href="JavaScript:document.bgColor='#0000FF'">blue background</a>

示例[编辑]

bookmarklets.com上可以找到大量链接,其中显示了可以在 JavaScript 中执行的各种功能。