我已经有onclick
事件用于在鼠标点击时更改div的边框颜色。
我希望能够在shift +点击时单独更改背景颜色,而无需更改边框颜色。
如何实现这一目标?
修改
多次点击和shift +点击的当前代码:
<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 - 由Jeffman解决
答案 0 :(得分:1)
在onclick
中,请务必参考event
,例如如果您使用的是属性:
<div onclick="clickHandler(event);" ... >
或者如果您稍后再分配:
divElement.onclick = function(event) {
event = event || window.event; // Support for older IE
// ...
};
或者如果你真的使用addEventListener
并且只是说onclick
作为一种速记:
divelement.addEventListener("click", function(event) {
// ...
}, false);
然后您可以参考event.shiftKey
标志来判断Shift是否已关闭。
更多the spec。
答案 1 :(得分:1)
最新代码。看到它在这里工作: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.
}
}
}
答案 2 :(得分:0)
Javascript.net解释了如何在http://www.javascripter.net/faq/ctrl_alt.htm
中执行所需操作