I already have onclick
event for changing border color of a div on mouse click.
I want to be able to change background color separately on shift + click, without changing border colors.
How to achieve this?
edit:
the current code for multiple clicks and shift+click:
<script>
var linkClick = 1;
function update_x(obj){
if (linkClick == 1){obj.style.border = 'solid 1px #eeeeee';};
if (linkClick == 2){obj.style.border = 'solid 1px red'};
if (linkClick == 3){obj.style.border = 'solid 1px rgba(50, 255, 50, 1)'};
if (linkClick == 4){obj.style.border = 'solid 1px rgba(70, 180, 255, 1)'};
if (linkClick == 5){obj.style.border = 'solid 1px yellow'};
if (linkClick >5 ) {obj.style.border = 'solid 1px #555555'; linkClick=0};
linkClick++;
}
</script>
<script>
function changeDivColor (event) {
event = event || window.event;
var myDiv = document.getElementById("b14")
if (event.shiftKey == true) {
myDiv.style.backgroundColor = "blue";
}
}
window.onload = function () {
document.getElementById("b14").onclick = function (event) {
changeDivColor (event);
update_x(this);
}
}
</script>
edit2 - solved by Jeffman
In your onclick
, make sure you refer to the event
, eg if you're using an attribute:
<div onclick="clickHandler(event);" ... >
or if you're assigning it later:
divElement.onclick = function(event) {
event = event || window.event; // Support for older IE
// ...
};
or if you're really using addEventListener
and just said onclick
as a kind of shorthand:
divelement.addEventListener("click", function(event) {
// ...
}, false);
Then you can refer to the event.shiftKey
flag to tell whether Shift is down.
More in the spec .
Latest code. See it work here: http://jsfiddle.net/jeffman/Y3QET/
var linkClick = 1;
function update_x(obj) {
if (linkClick == 1){obj.style.border = 'solid 1px #eeeeee';};
if (linkClick == 2){obj.style.border = 'solid 1px red'};
if (linkClick == 3){obj.style.border = 'solid 1px rgba(50, 255, 50, 1)'};
if (linkClick == 4){obj.style.border = 'solid 1px rgba(70, 180, 255, 1)'};
if (linkClick == 5){obj.style.border = 'solid 1px yellow'};
if (linkClick >5 ) {obj.style.border = 'solid 1px #555555'; linkClick=0};
linkClick++;
}
function changeDivColor (el, event) {
if (event.shiftKey == true) {
el.style.backgroundColor = "blue";
}
}
window.onload = function () {
var i = 1, len = 5; // len is the number of elements using the b1 id pattern
for (i; i <= len; i++) {
document.getElementById("b" + i).onclick = function (event) {
event = event || window.event;
changeDivColor (this, event);
update_x(this); // or whatever your other function is.
}
}
}
Javascript.net在http://www.javascripter.net/faq/ctrl_alt.htm上有关于如何做你需要的解释
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.