[英]How to get an element's style after waiting for a delay using JavaScript?
在单击事件后的一定时间后,我需要检查li
元素的font-weight
属性的值。 下面的代码循环遍历所有li
元素,因此每当其中一个元素触发click
event
时,它应该获取font-weight
属性的值和 output 到控制台,但实际上它返回一个空行:
const pages = document.querySelectorAll("#pagination li");
pages.forEach(page => page.addEventListener('click', function(e) {
let fontWeight = e.target.style.fontWeight;
console.log(fontWeight)
setTimeout(() => {
console.log(fontWeight)
}, 1000)
}));
document.querySelector('#pagination li:nth-of-type(3)').click()
尝试使用
window.getComputedStyle(e.target).fontWeight;
我不完全确定为什么会发生这种情况,但我认为这与样式应用于元素的方式有关。
您的代码片段中没有 HTML 代码,因此我添加了一些 HTML 以使用您提供的 JavaScript 代码。
我不知道为什么document.querySelector('#pagination li:nth-of-type(3)').click()
对你不起作用。 您使用的 HTML 可能有问题。 它与下面的 HTML 一起使用,在代码片段中单击 RUN 后,console.log 中会出现bold
代码中的以下行将在单击时读取字体粗细:
let fontWeight = e.target.style.fontWeight;
所以你的第一个console.log
将是正确的。 但是,您的第二个console.log
只会返回这个相同的值,因为您没有从e.target
访问fontWeight
属性。 我只能猜测您的li
元素上没有设置字体粗细,或者您的 CSS 选择器无法正常工作。 这可能就是为什么单击数字时不会返回任何内容的原因。
在下面的代码中,我们可以在liElement
变量中存储对e.target
的引用,然后我们可以在setTimeout
回调中访问它。 这样,代码将访问liElement
两次,一次是单击,另一次是一秒后。 如果字体粗细发生变化,那么您将在console.log
中看到这一点
const pages = document.querySelectorAll("#pagination li"); const fontWeightOnClick = document.getElementById("fontWeightOnClick"); const fontWeightAfter1Second = document.getElementById("fontWeightAfter1Second"); pages.forEach(page => page.addEventListener('click', function(e) { let liElement = e.target; console.log(liElement.style.fontWeight, "on click"); setTimeout(() => { console.log(liElement.style.fontWeight, "after 1 second"); }, 1000) })); document.querySelector('#pagination li:nth-of-type(3)').click()
#pagination { list-style: none; font-size: 1.5rem; } #pagination li { display: inline-block; }
<ul id="pagination"> <li>1</li> <li>2</li> <li style="font-weight: bold;">3</li> <li style="font-weight: 800;">4</li> <li>5</li> <li>6</li> <li>7</li> <li>8</li> <li>9</li> <li style="font-weight: bolder;">10</li> <li style="font-weight: 600;">11</li> <li>12</li> <li>13</li> <li>14</li> <li>15</li> <li>16</li> </ul> <p>Click on '3', '4', '10' or '11' to return the weight. Clicking on any other number will not return the weight</p>
/* ```*/ //400 - norm, 700 - bold in many browser apps var timing=1000; for(itr=1;itr<7;itr++){ ment = document.createElement('li'); ment.setAttribute('onclick','if(this.id%2==0){this.style.fontWeight=`bold`}'); ment.id=itr; ment.innerText=itr; document.body.appendChild(ment); } var eventually; var code='alert(getComputedStyle(eventually.target).fontWeight)'; document.body.setAttribute(`onclick`,`eventually=event;setTimeout(code,timing)`); /* ```*/
为什么这个代码:它被简化了,没有分页,但仍然提供改变字体粗细的能力(当你点击一个偶数li
时,它变成像当前页面链接一样的粗体)。
在第二次点击后,您会得到项目的getComputedStyle
作为数字400 或700 在浏览器中最常见的警报。 试试看。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.