如何设置键来改变节点的样式?

时间:2014-09-21 12:19:04

标签: javascript html firefox key greasemonkey

我正在使用Greasemonkey的用户脚本,我想设置一个键,通过按键将display:""的样式none更改为block,反之亦然。 " Home"在这种情况下)。

var bluebar = document.getElementById('pagelet_bluebar');
bluebar.style.display = "none";
document.addEventListener("keydown", function (e) {
    if (e.keyCode == 36) {
        showhideui();
    }
}, false);
function showhideui() {
    if (bluebar.style.display = "none") {
        bluebar.style.display = "block";
    } else if (bluebar.style.display = "block") {
        bluebar.style.display = "none";
    }
}

解决方案是在条件中添加==而不是=

if (bluebar.style.display == "none")
else if (bluebar.style.display == "block")

1 个答案:

答案 0 :(得分:1)

在比较中使用=====代替单=个签名 请查看此comparison operators

链接
 var bluebar = document.getElementById('pagelet_bluebar');
   document.addEventListener("keydown", function (e) {
       if (e.keyCode === 36) { //press "Home" key change to block/none
           showhideui();
       }
   }, false);
   function showhideui() {
       if (bluebar.style.display == "none") { //if is none
           bluebar.style.display = "block" ; //change to block
       } else if (bluebar.style.display == "block" || bluebar.style.display == "") { //if is block
           bluebar.style.display = "none"; //change to none
       }
   }

Ps:如果只有这两种可能性,你甚至可以使用更合成的方式:

(bluebar.style.display == "block" || bluebar.style.display == "") ? bluebar.style.display = "none" : bluebar.style.display = "block";