我有几个元素,当它们悬停时,它们的高度会稍微增加。单击其中一个时,我需要在该元素未悬停时获得该元素的高价。
window.getComputedStyle(elem, null).height
给我悬停的高度。与window.getComputedStyle(elem, ':not(:hovered)').height
相同。
不幸的是,正常高度和悬停高度之间的差不是恒定的,所以我不能只减去该常数。
编辑:添加了一个最小的工作示例:
function onClick(target) {
const hoveredHeight = window.getComputedStyle(target, ':hovered').height;
const normalHeight = window.getComputedStyle(target, null).height;
alert('The hovered height is ' + hoveredHeight + ', and the normal height is ' + normalHeight);
}
p {
position: absolute;
margin: 0px;
top: 50%;
transform: translateY(-50%);
}
#hover-me {
position: relative;
height: 50px;
width: 100px;
background-color: #999;
vertical-align: middle;
transition: height 0.1s linear;
}
#hover-me:hover {
height: 100px;
}
<div id="hover-me" onclick="onClick(this)"><p>Click me</p></div>
首先,:hovered是window.getComputedStyle()函数的无效选项,因为:hovered不是pseudo-elements,而是pseudo-classes。
所以您的句子window.getComputedStyle(target, ':hovered').height
与window.getComputedStyle(target).height
或您传递到第二个参数位置的任何值具有相同的结果。
如果要在悬停前存储元素的高度,则有很多方法。我在代码段中演示了使用javascript和onmouseenter和onmouseleave事件的一种方法。
var originalHeight;
function onClick(target) {
const currentHeight = window.getComputedStyle(target).height;
alert('The hovered height is ' + currentHeight + ', and the normal height is ' + originalHeight);
}
function onMouseEnter(target) {
originalHeight = window.getComputedStyle(target).height;
// set new height
target.style.height = '100px';
}
function onMouseLeave(target) {
// reset the original height
target.style.height = originalHeight;
}
p {
position: absolute;
margin: 0px;
top: 50%;
transform: translateY(-50%);
}
#hover-me {
position: relative;
height: 50px;
width: 100px;
background-color: #999;
vertical-align: middle;
transition: height 0.1s linear;
}
<div id="hover-me" onclick="onClick(this)" onmouseenter="onMouseEnter(this)" onmouseleave="onMouseLeave(this)"><p>Click me</p></div>