-
随机颜色的几种实现方法
已知hex的颜色值是从#000000到#ffffff,后面六位是16进制数,相当于“0x000000”到“0xffffff”。这实现的思路是将hex的最大值ffffff先转换为10进制,进行random后再转换回16进制。(我认为这个颜色随机最好看)
'#'+Math.floor(Math.random()*16777215).toString(16)
基本实现4的改进,利用左移运算符把0xffffff转化为整型。这样就不用记16777215了。由于左移运算符的优先级比不上乘号,因此随机后再左移,连Math.floor也不用了。
'#'+(Math.random()*0xffffff<<0).toString(16)
修正上面版本的bug(无法生成纯白色与hex位数不足问题)
'#'+('00000'+(Math.random()*0x1000000<<0).toString(16)).substr(-6)
-
显示,隐藏文字
<!DOCTYPE html>
<html>
<body>
<p id="p1">暮云收剧清寒,银汉无声转玉盘。<br>
此生此夜不长好,明月明年何处看。 </p>
<input type="button" value="隐藏文本" onclick="document.getElementById('p1').style.visibility='hidden'" />
<input type="button" value="显示文本" onclick="document.getElementById('p1').style.visibility='visible'" />
</body>
</html>
- 替换文字
<!DOCTYPE html>
<html>
<body>
<p>点击按钮就可以执行 <em>displayDate()</em> 函数。</p>
<button onclick="displayDate()">点击这里</button>
<script>
function displayDate()
{
document.getElementById("demo").innerHTML=Date();
}
</script>
<p id="demo"></p>
</body>
</html>
网友评论