<分区>
编辑问题以包含 desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem .这将有助于其他人回答问题。
关闭 5 年前。
标签 javascript html css
<分区>
编辑问题以包含 desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem .这将有助于其他人回答问题。
关闭 5 年前。
我有一个 <button>
我想要具有 3D 效果的元素。为了创建 3D 效果,我添加了一个 box-shadow
到按钮,单击按钮时,box-shadow
关闭,我给它一个相对位置来给出被按下的效果(你可以从下面的代码笔中得到更好的想法)。
我还需要使用按钮的点击事件来触发一些 javascript。问题是,如果用户在按钮顶部附近单击,则永远不会触发 click 事件,因为一旦应用了相对位置,用户单击的位置(在单击时位于按钮上)是现在在按钮上方,因此没有点击被注册。
我真的被这个难住了,我找不到让它工作的方法,所以我真的很感激你的帮助。谢谢!
这是一个link to the codepen .
最佳答案
尝试将按钮的内容包装在 span
中,然后操作那个,这样按钮的实际位置就不会改变。
var button = document.querySelector('button');
button.addEventListener('click',function(){
console.log('The button was clicked');
});
button {
background-color: transparent;
border: none;
}
button span {
background-color: lightblue;
padding: 1em;
display: block;
margin: 0 auto;
border-radius: 10px;
box-shadow: 0 0.5em skyblue;
}
button:active span {
position: relative;
top: 0.5em;
box-shadow: none;
}
<button><span>Click Me</span></button>
关于javascript - 相对定位元素原始位置的点击事件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50613049/