在我的代码中,当您将鼠标悬停在元素上时,它们周围会出现红色边框。鼠标移开时,边框将被删除。
正如你所看到的,当你做mousoevers时,元素会随着边框增加宽度和高度而跳跃。
有没有办法阻止跳跃?
document.addEventListener("mouseover", eOnMouseOver, true);
document.addEventListener("mouseout", eOnMouseOut, true);
function eOnMouseOver(e) {
e.target.style.border = "2px solid red";
}
function eOnMouseOut(e) {
e.target.style.border = "";
}
<div style="border:1px black solid;">Mouseover me</div>
<a href="#">Mouseover me</a>
答案 0 :(得分:1)
是的,有。您必须将box-sizing: borde-box
与供应商前缀一起使用才能实现此目的。这就是我的意思:
document.addEventListener("mouseover", eOnMouseOver, true);
document.addEventListener("mouseout", eOnMouseOut, true);
function eOnMouseOver(e) {
e.target.style.outline = "2px solid red";
}
function eOnMouseOut(e) {
e.target.style.outline = "";
}
* {
box-sizing: border-box;
-webkit-box-sizing: border-box;
-moz-box-sizing: border-box;
-ms-box-sizing: border-box;
-o-box-sizing: border-box;
}
<div style="border:1px black solid;">Mouseover me</div>
<a href="#">Mouseover me</a>
但是,在这种情况下,您不需要使用javascript。请改用CSS伪类,如下所示:
* {
box-sizing: border-box;
-webkit-box-sizing: border-box;
-moz-sizing: border-box;
-ms-sizing: border-box;
-o-sizing: border-box;
}
*:hover {
outline: 2px solid red;
}
<div style="border:1px black solid;">Mouseover me</div>
<a href="#">Mouseover me</a>
答案 1 :(得分:1)
指定透明边框,鼠标悬停时为边框添加颜色
div,
a {
border: 1px solid transparent;
}
div:hover,
a:hover {
border-color: red;
}
<div>Mouseover me</div>
<a href="#">Mouseover me</a>
答案 2 :(得分:0)
function eOnMouseOver(e) {
e.target.style.border = "2px solid red";
e.target.style.marginLeft = "-2px";
e.target.style.marginTop = "-2px";
}
function eOnMouseOut(e) {
e.target.style.border = "";
e.target.style.marginLeft = "";
e.target.style.marginTop = "";
}
试试吧。边距偏移应该将元素向上拉并向左移动2px边界正在推动,理论上保持元素稳定。未经测试。
编辑:另一种解决方案是执行以下操作......
function eOnMouseOver(e) {
e.target.style.border = "2px solid red";
}
function eOnMouseOut(e) {
e.target.style.border = "2px solid transparent";
}
然后只需将eOnMouseOut(e)函数中的边框应用于基本元素,这样它就不会在第一个mouseOver上反弹。
答案 3 :(得分:0)
如何使用框阴影?它不会影响您的布局,纯粹是视觉效果,并保持div的border属性完好无损:
document.addEventListener("mouseover", eOnMouseOver, true);
document.addEventListener("mouseout", eOnMouseOut, true);
function eOnMouseOver(e) {
e.target.style.boxShadow = "0 0 0 2px red";
}
function eOnMouseOut(e) {
e.target.style.boxShadow = "none";
}
<div style="border:1px black solid;">Mouseover me</div>
<a href="#">Mouseover me</a>