gpt4 book ai didi

javascript - 当检测到单击 div 时更改 div 的样式

转载 作者:太空宇宙 更新时间:2023-11-04 01:45:49 24 4
gpt4 key购买 nike

我在 Bootstrap 中有 8 个 div,当我使用以下代码单击它时,我可以更改它的样式;

    $(document).ready(function() {
$(".continue--btn").hide();

if ($('.generator--templates').click(function(){
$('.continue--btn').show();
$(this).css("background", "#03A9F3");
$(this).find('.generator--templates__description, .generator--templates__purpose').css("color", "#fff");
})
);

这也显示了一个继续按钮。

但是,接下来我要做的是当我单击除 div 以外的任何地方时,div 将获得他的默认样式并且该按钮将再次消失。

我无法解决这个问题。

我已经试过了:

var templates = document.getElementsByClassName('.generator--templates');

window.onclick = function(event){
if (event.target == templates){
templates.style.background = "#fff";
}
}

最佳答案

首先请注意,您的语法不正确,因为您在 if 语句中放置了一个 click() 处理程序。

其次,templates 将是从 getElementsByClassName 返回的元素集合。因此,将它与 event.target 中的元素进行比较永远不会匹配。

要解决此问题,请在 document 上放置一个点击处理程序并检查目标元素的类,如下所示:

$(document).ready(function() {
$('.generator--templates').click(function() {
$('.continue--btn').show();
$(this).find('.generator--templates__description, .generator--templates__purpose').addBack().addClass('active');
})

$(document).on('click', function(e) {
var $target = $(this);
if ($target.is('.generator--templates') || $target.closest('.generator--templates').length) {
$('.continue--btn').hide();
$('.generator--templates').removeClass('active');
}
});
});
.continue--btn { 
display: none;
}

.generator--templates.active,
.generator--templates__description.active,
.generator--templates__purpose.active {
color: #FFF;
}

请注意,此处使用的是 CSS 而不是 css(),这应该尽可能避免,因为它将 JS 逻辑与 UI 联系得太紧密。

关于javascript - 当检测到单击 div 时更改 div 的样式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44584008/

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