简体   繁体   中英

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:

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:

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. 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:

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

Sure. Use a 'mouseover' event attached to the button.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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