gpt4 book ai didi

javascript - 通过 onclick 和使用 getElementsByName 更改 div css 颜色

转载 作者:太空宇宙 更新时间:2023-11-03 21:37:56 27 4
gpt4 key购买 nike

这是我到目前为止使用 CSS、Javascript 和 HTML 所做的。如果您单击红色圆圈,它将变为黄色这是可行的,但是,我只想添加一些功能,如果用户在 div 之外的任何地方单击,则 div 将恢复为原始颜色。

我该怎么做?

这是我的代码:

HTML:

<html>
<body>
<div id="circle" name="color" onclick="changeColor()"></div>
</body>
</html>

CSS:

#circle{
height: 100px;
width: 100px;
border-radius: 100px;
background: #F00;
border: 2px solid ;
}

JS:

function changeColor() {
document.getElementsByName('color')[0].style.background="#FF0";
}

谢谢..:)

最佳答案

最灵活的方法是在您的 CSS 中添加一个 .active 类,并在点击时将该类应用于您的圈子。

如果你想捕获圆圈外的点击,你必须在 body 上设置事件监听器,然后检查 e.target 看它是否与你的元素匹配。

var circle = document.getElementById('circle');
document.onclick = function(e) { //Set the event handler in JavaScript, not in HTML.
if (e.target === circle) { //e.target is the clicked element.
circle.classList.add("active");
}
else {
circle.classList.remove("active");
}
}

然后在你的 CSS 中:

#circle{
height: 100px;
width: 100px;
border-radius: 100px;
background: #F00;
border: 2px solid ;
}
<strong>#circle.active {
background: #FF0;
}</strong>

Toggle 表示如果该类不存在,它将应用该类,如果存在,则将其删除。现在,如果您想添加额外的样式以在点击时发生,您只需将它们添加到 #circle.active 选择器即可。

Demo

关于javascript - 通过 onclick 和使用 getElementsByName 更改 div css 颜色,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25500293/

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