gpt4 book ai didi

javascript - 如何使用 JavaScript 在函数上指定源和目标?

转载 作者:行者123 更新时间:2023-11-30 10:04:33 25 4
gpt4 key购买 nike

我需要这个函数来在鼠标悬停在按钮上时更改窗体的边框颜色。我得到了预期的结果,但是该功能影响了所有页面表单。我想确定哪个按钮影响每个表单。

如何在函数中指定源 ID 和目标 ID?

View demo

<head>
<script>
function chbg(color) {
document.getElementById('b').style.backgroundColor = color;
document.getElementById('d').style.backgroundColor = color;
}
</script>
</head>

<body>
<div id="a" onmouseover="chbg('red')" onmouseout="chbg('white')">A - This should effect B only</div>
<div id="b">B - This is neutral</div>
<div id="c" onmouseover="chbg('blue')" onmouseout="chbg('white')"> C - This should effect D only</div>
<div id="d">D - This is neutral</div>
</body>

更新:

解决了!谢谢大家的帮助。

View solution

最佳答案

您可以使用自定义 data-* 属性指定目标:

function chbg(e) {
document.querySelector(this.dataset.chbgTarget)
.style.backgroundColor = this.dataset[
'chbgColor' + (e.type == 'mouseover' ? 'Over' : 'Out')
];
}
var els = document.querySelectorAll('.chbg');
for(var i=0; i<els.length; ++i) {
els[i].addEventListener('mouseover', chbg);
els[i].addEventListener('mouseout', chbg);
}
<div id="a" class="chbg"
data-chbg-color-over="red"
data-chbg-color-out="white"
data-chbg-target="#b">
A - This should effect B only
</div>
<div id="b">B - This is neutral</div>
<div id="c" class="chbg"
data-chbg-color-over="blue"
data-chbg-color-out="white"
data-chbg-target="#d">
C - This should effect D only
</div>
<div id="d">D - This is neutral</div>

如果在 mouseout 时你只想移除颜色,考虑这个:

function chbg(e) {
document.querySelector(this.dataset.chbgTarget)
.style.backgroundColor =
e.type == 'mouseover' ? this.dataset.chbgColor : '';
}
var els = document.querySelectorAll('.chbg');
for(var i=0; i<els.length; ++i) {
els[i].addEventListener('mouseover', chbg);
els[i].addEventListener('mouseout', chbg);
}
<div id="a" class="chbg"
data-chbg-color="red"
data-chbg-target="#b">
A - This should effect B only
</div>
<div id="b">B - This is neutral</div>
<div id="c" class="chbg"
data-chbg-color="blue"
data-chbg-target="#d">
C - This should effect D only
</div>
<div id="d">D - This is neutral</div>

关于javascript - 如何使用 JavaScript 在函数上指定源和目标?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29884688/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com