我正在尝试通过html样式属性在js中执行函数,但无法使其正常工作。
我有一个js函数(例如jscode),可以使用快捷方式。我想通过尝试使代码在网页上的html类具有600px(加载栏具有600px,完成后,代码应以1ms的延迟)运行时自行执行来规避这一点
function test() {
setTimeout(function () { jscode(); }, 1);
}
var htmltest = document.getElementsByClassName("loadingbar");
var htmlteststyle = htmltest[0].style;
if (htmlteststyle.width == '600px') {
console.log("success");
test();
}
这根本不起作用,控制台消息不会出现,并且js文件仅在出现此代码段之前执行自身。
我只是开始玩js和html,不知道我出了什么问题,也许这是完全错误的方法?
任何建议表示赞赏。
答案 0 :(得分:1)
是的,您的方法完全落后。无论您是使用轮询(当前正在执行的操作)还是通过突变观察器,尝试收听样式的更改都是非常糟糕的。原因是因为它比需要的要复杂得多,并且可能会损害DOM性能。
相反,您希望绑定到更新进度条的代码中。它应该有一个progress变量,所以当它达到100%时只需运行代码即可。
示例代码:
// Inside the code that updates the bar
if (progress === 100 && !hasCompleted){
hasCompleted = true;
console.log('success!');
}
答案 1 :(得分:0)
您可以使用Mutation Observer自动检测宽度变化。我在此处执行宽度变化,请点击此处按钮。
function test() {
setTimeout(function() {
jscode();
}, 1);
}
function jscode() {
console.log("will run after 1 second")
}
var target = document.getElementsByClassName('loadingbar')[0];
// create an observer instance
var observer = new MutationObserver(function(mutations) {
mutations.forEach(function(mutation) {
let width = mutation.target.style.width
if (width == "600px") {
console.log("hii")
test();
// execute your function here
}
});
});
// configuration of the observer:
var config = {
attributes: true,
childList: true,
characterData: true
};
// pass in the target node, as well as the observer options
observer.observe(target, config);
// chnaging width to 600px;
function changewidth()
{
document.getElementById("a").style.width = "600px";
}
.loadingbar {
border: 1px solid black;
width: 100px
}
<html>
<div class="loadingbar" id="a">HI</div>
<button onclick="changewidth()">Change width</button>
</html>
答案 2 :(得分:0)
根据您对问题的了解,我已经重写了您的功能。 该函数检查元素的宽度,如果宽度为600px,它将成功console.log,然后为jsCode函数设置一个延迟。如果宽度不是600px,则该函数将设置一个超时时间,使其在一秒钟后自动运行。
function checkWidth(){
var htmltest = document.getElementsByClassName("loadingbar");
var htmlteststyle = htmltest[0].style;
if(htmlteststyle.width == '600px'){
console.log("success");
setTimeout(function(){ jscode(); }, 1);
} else {
setTimeout(checkWidth, 1000);
}
}
答案 3 :(得分:0)
尝试使用MutationObserver,以便您可以收听样式更改事件。见