javascript - e.clientX - rect.left 返回 false 值 // vanilla JS
问题描述
我目前正在构建一个按钮,它悬停在其渐变中。一切正常,除了渐变的位置,它应该由e.clientX - rect.left
. 将按钮悬停在其左边缘,结果为 0%(完美!)。但是将它悬停在右边缘,会返回 150% 左右。
非常感谢你的帮助!
let btn = document.getElementById("btn");
btn.onmousemove = function (e) {
let rect = e.target.getBoundingClientRect();
let x = e.clientX - rect.left;
btn.style.setProperty("--x", x + "%");
};
:root {
--x: 0%;
}
body {
font-family: "Open Sans", sans-serif;
margin: 0;
}
.wrapper {
position: absolute;
top: calc(50% - 25px);
left: calc(50% - 75px);
}
button {
height: 50px;
min-height: 50px;
min-width: 150px;
border: none;
position: relative;
background: linear-gradient(
90deg,
rgba(7, 22, 103, 1) 0%,
rgba(55, 83, 198, 1) 100%
);
color: white;
border-radius: 10px;
padding: 0;
}
button:hover {
background: none;
cursor: pointer;
}
button::after {
content: "";
position: absolute;
background: linear-gradient(
90deg,
rgba(7, 22, 103, 1) 0%,
rgba(55, 83, 198, 1) var(--x),
rgba(7, 22, 103, 1) 100%
);
height: 100%;
width: 100%;
border-radius: 10px;
top: 0;
left: 0;
display: none;
z-index: -1;
}
button:hover::after {
display: inline;
}
span {
margin: 0 30px;
}
<link
href="https://fonts.googleapis.com/css?family=Fjalla+One|Open+Sans&display=swap"
rel="stylesheet"
/>
<div class="wrapper">
<button id="btn"><span>Click here</span></button>
</div>
解决方案
当您检索像素值时,请勿%
在 css 中使用px
let btn = document.getElementById("btn");
btn.onmousemove = function (e) {
let rect = e.target.getBoundingClientRect();
let x = e.clientX - rect.left;
btn.style.setProperty("--x", x + "px");
};
:root {
--x: 0%;
}
body {
font-family: "Open Sans", sans-serif;
margin: 0;
}
.wrapper {
position: absolute;
top: calc(50% - 25px);
left: calc(50% - 75px);
}
button {
height: 50px;
min-height: 50px;
min-width: 150px;
border: none;
position: relative;
background: linear-gradient(
90deg,
rgba(7, 22, 103, 1) 0%,
rgba(55, 83, 198, 1) 100%
);
color: white;
border-radius: 10px;
padding: 0;
}
button span { width:100%; }
button:hover {
background: none;
cursor: pointer;
}
button::after {
content: "";
position: absolute;
background: linear-gradient(
90deg,
rgba(7, 22, 103, 1) 0%,
rgba(55, 83, 198, 1) var(--x),
rgba(7, 22, 103, 1) 100%
);
height: 100%;
width: 100%;
border-radius: 10px;
top: 0;
left: 0;
display: none;
z-index: -1;
}
button:hover::after {
display: inline;
}
span {
margin: 0 30px;
}
<link
href="https://fonts.googleapis.com/css?family=Fjalla+One|Open+Sans&display=swap"
rel="stylesheet"
/>
<div class="wrapper">
<button id="btn">Click here</button>
</div>
推荐阅读
- django - 如何从 django 中的另一个模型字段更新模型字段?
- gitlab - 使用 CI_COMMIT_BRANCH 分支名称作为文件路径
- java - 在传递给 Java 中的方法时修改对象
- java - 注入内联 Mockito 静态方法
- oauth2-playground - GMB Api 位置列表
- javascript - 按日期减少对象
- discord - 当他们做出某种反应时,如何将 Discord 用户 ID 添加到机器人嵌入消息中?
- python - 我正在获取日期和收入_rates_usd 列,但是当我尝试获取两个日期之间的范围时,我得到了错误
- keras - 通过将图像传递给对象检测模型来生成图像类的裁剪
- r - R使用dplyr按组计算加权统计