Javascript 突出显示 div onclick
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/30810821/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Highlight div onclick
提问by Justinas Talandis
I have a question, what jQuery code need to be used, to highlight DIV in list on click? I have 8 Div's, I need to highlight one which is clicked, and when clicking on next one, previous is no longer highlighted.
我有一个问题,需要使用什么 jQuery 代码才能在单击时突出显示列表中的 DIV?我有 8 个 Div,我需要突出显示一个被点击的,当点击下一个时,上一个不再突出显示。
回答by Namit Singal
Ok, So try this:-
好的,所以试试这个:-
JSFiddle- http://jsfiddle.net/dtzjN/198/
JSFiddle- http://jsfiddle.net/dtzjN/198/
All you need to do is, have a common class in all the divs, on click, remove the color class from every other div, and add a color class to the clicked div.
您需要做的就是,在所有 div 中都有一个公共类,单击时,从每个其他 div 中删除颜色类,然后向单击的 div 添加一个颜色类。
<div class="divs">
Thumb1
</div>
<div class="divs">
Thumb1
</div>
<div class="divs">
Thumb1
</div>
<div class="divs">
Thumb1
</div>
JS
JS
var addclass = 'color';
var $cols = $('.divs').click(function(e) {
$cols.removeClass(addclass);
$(this).addClass(addclass);
});
CSS
CSS
.color {
background-color: yellow;
}
source :- How can I highlight a selected list item with jquery?
Modified it as per requirement.
根据要求修改了它。
回答by Awena
Try the below
试试下面的
$(document).ready(function() {
$Divs = $("div");
$Divs.click(function() {
$Divs.removeClass("highlight");
$(this).addClass("highlight");
});
});
.highlight {
background: green;
}
div {
display: block;
width: 100px
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<ul>
<li>
<div>First Div</div>
</li>
<li>
<div>Second Div</div>
</li>
</ul>
回答by mapodev
<ul>
<li><div>Html 1</div></li>
<li><div>Html 2</div></li>
<li><div>Html 3</div></li>
</ul>
And the JS
和 JS
$(document).ready(function() {
$("li div").click(function() {
$("li div").each(function() {
$(this).css("background-color", "transparent");
});
$(this).css("background-color", "#ff3300");
});
});
回答by AshBringer
You can try something like this maybe :
你可以尝试这样的事情:
$('.mainDiv').on('click','.divs',function () {
$(this).parent().find('.divs').css('background-color', '');
$(this).css('background-color', '#00fff0');
});

