gpt4 book ai didi

javascript - 将类添加到动态元素的主体,在页面上的任意位置再次单击后删除

转载 作者:行者123 更新时间:2023-11-30 12:04:24 25 4
gpt4 key购买 nike

我想给 <body> 添加一个类标记使光标在单击按钮时成为十字准线。当我单击页面上的任何位置时,我希望删除此类。

目前我点击按钮,添加类,然后立即删除。

$('button').on('click', function() {
$('body').addClass('changeCursor');
}

$('html').on('click', '.changeCursor', function(){
$('body.changeCursor').removeClass('changeCursor');
});

最佳答案

它被直接删除,因为在您的按钮单击处理程序将类添加到 body 之后,按钮单击传播到 html 元素。然后 html 元素的处理程序运行,找到 body.changeCursor 并将其删除。

只需在第一个处理程序中停止传播:

$('button').on('click', function(e) {
$('body').addClass('changeCursor');
e.stopPropagation();
});

实例:

$('button').on('click', function(e) {
$('body').addClass('changeCursor');
e.stopPropagation();
});

$('html').on('click', '.changeCursor', function() {
$('body.changeCursor').removeClass('changeCursor');
});
.foo {
display: none;
}
body.changeCursor .foo {
display: inline-block;
}
<button type="button">Click me to add</button>
<p>Click here or anywhere but the button above to remove</p>
<p class="foo">I'm only showing when <code>body</code> has <code>changeCursor</code></p>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>

我使用了stopPropgation,它停止传播,但如果您不需要默认操作发生,您可以返回false,它同时执行 stopPropgation preventDefault:

$('button').on('click', function() {
$('body').addClass('changeCursor');
return false;
});

实例:

$('button').on('click', function() {
$('body').addClass('changeCursor');
return false;
});

$('html').on('click', '.changeCursor', function() {
$('body.changeCursor').removeClass('changeCursor');
});
.foo {
display: none;
}
body.changeCursor .foo {
display: inline-block;
}
<button type="button">Click me to add</button>
<p>Click here or anywhere but the button above to remove</p>
<p class="foo">I'm only showing when <code>body</code> has <code>changeCursor</code></p>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>

关于javascript - 将类添加到动态元素的主体,在页面上的任意位置再次单击后删除,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35626592/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com