我有这个简短的例子:
<fieldset id="packType">
<label>1</label>
<label>2</label>
<label>3</label>
</fieldset>
$("#packType label").on("click", function(e) {
$(this).css({ "border": "2px solid #ff4141" });
});
我想仅对您单击的项目应用红色边框,其余部分应为border: none;
。我怎样才能做到这一点?你能帮帮我吗?
答案 0 :(得分:1)
你可以这样做
var $lbl = $("#packType label").on("click", function(e) {
$lbl.css("border", "none");
// set border none to all elements
$(this).css("border", "2px solid #ff4141");
// set border to clicked element
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<fieldset id="packType">
<label>1</label>
<label>2</label>
<label>3</label>
</fieldset>
或使用siblings()
,它选择元素的兄弟姐妹
$("#packType label").on("click", function(e) {
$(this).css("border", "2px solid #ff4141")
//set border to clicked element
.siblings().css("border", "none");
// set border none to all siblings of clicked element
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<fieldset id="packType">
<label>1</label>
<label>2</label>
<label>3</label>
</fieldset>
答案 1 :(得分:0)
您可以将边框设置为单击的元素,并使用.siblings()
选择器选择其他元素并将相应的边框设置为无。
$("#packType label").on("click", function(e) {
$(this).css({
"border": "2px solid #ff4141"
});
$(this).siblings().css({
"border": "none"
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<fieldset id="packType">
<label>1</label>
<label>2</label>
<label>3</label>
</fieldset>
答案 2 :(得分:0)
如果标签上没有其他样式,则可以完全删除样式属性:
$(this).css({ "border": "2px solid #ff4141" })
.siblings('label').removeAttr('style'); // will clean the style attribute.
如果您需要使用其他样式并且仅定位要删除的边框,请使用以下命令:
$(this).css({ "border": "2px solid #ff4141" })
.siblings('label').css('border','none'); // will remove borders.
答案 3 :(得分:0)
您应该创建一个CSS类,将CSS类添加到当前单击的标签。
要获得所需的结果,可以使用各种API,即.siblings()
,addClass()
和removeClass()
$("#packType label").on("click", function(e) {
$(this).addClass('withBorder').siblings().removeClass('withBorder');
});
.withBorder {
border: 2px solid #ff4141;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<fieldset id="packType">
<label>1</label>
<label>2</label>
<label>3</label>
</fieldset>