简体   繁体   English

按住键时更改悬停样式

[英]Change style on hover while a key is held down

I've set up a style to turn a single-cell table, for example: 我已经设置了一种样式来转换单单元格表,例如:

<TABLE ONCLICK='goSomewhere("http://en.wiktionary.org/wiki/yes", "http://en.wiktionary.org/wiki/no")' CLASS="mybutton">
    <TR>
        <TD>This is a button</TD>
    </TR>
</TABLE>

Into a button via CSS such as: 通过CSS进入按钮,例如:

table.mybutton {
    border : 1px solid;
    border-radius : 8px;
    border-spacing : 2px;
    font-size : 80%;
    display : inline-table;
    cursor : pointer;
}
table.mybutton:hover {
    background-color : black;
    color : white;
}

I've managed to get it to visit one of two URLs depending on whether the Shift key is held down via this Javascript: 我设法让它访问两个URL之一,具体取决于是否通过此Java脚本按住Shift键:

var shift = false;

function shiftHandler(event) {
    shift = event.shiftKey;
};

window.addEventListener("keydown", shiftHandler, false);
window.addEventListener("keypress", shiftHandler, false);
window.addEventListener("keyup", shiftHandler, false);

function goSomewhere(url1, url2) {
    if (shift) {
        window.location.href = url2;
    } else {
        window.location.href = url1;
    }
}

function goSomewhereElse(url) {
    window.location.href = url;
}

The last piece is that I'd like the background color of the button while hovering to change depending on whether the Shift key is held as well. 最后一点是,我希望在悬停时根据是否按住Shift键来更改按钮的背景色。 Can this be done? 能做到吗? Can it be done without extra libraries? 无需额外的库就可以完成吗?

Example Fiddle 小提琴的例子

I would do it by changing an element's class when the key is pressed or released. 我可以通过在按下或释放键时更改元素的类来实现。 Adding a line to your code: 在代码中添加一行:

function shiftHandler(event) {
    shift = event.shiftKey;
    document.body.className = shift ? 'shift-pressed' : '';
};

Then you can select that class in your CSS: 然后,您可以在CSS中选择该类:

.shift-pressed table.mybutton:hover {
    background-color: green;
    color: white;
}

Sure. 当然。 Use a 'mouseover' event attached to the button. 使用附加在按钮上的“ mouseover”事件。

var element = document.getElementById("#button-id");
element.addEventListener("mouseover", function(event) {
    if (shift) {
         //make the color change here
    }
})

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM