gpt4 book ai didi

jquery - 如何以编程方式覆盖表单提交上的 select2 css?

转载 作者:行者123 更新时间:2023-11-28 00:30:39 26 4
gpt4 key购买 nike

我试图突出显示当用户尝试提交表单时未填写的 select2 选择。我不知道如何从文档加载中覆盖我预先存在的 css 样式。

这是我的 jquery 尝试:

var $requiredUnfilledItems = $(".required:not(.filled)");
if ($requiredUnfilledItems.length > 0) {
$requiredUnfilledItems.each( function(){
$(this).addClass('warning-border');
});
}

和我的 .warning-border 的 CSS:

.warning-border { 
outline: none !important;
border-color: red !important;
box-shadow: 0 0 10px red !important;
}

试图覆盖它:

.select2-container--default .select2-selection--single {
width: 100%;
padding-left: 4px;
height: 100%;
border: thin solid lightgray;
height: 30px;
}

但它不起作用。我也尝试过这个(这可能只是证明我还没有掌握 css):

.warning-border, .select2-container.warning-border { 
outline: none !important;
border-color: red !important;
box-shadow: 0 0 10px red !important;
}

帮忙吗?

最佳答案

我的建议是不要使用 !important 而是理解 CSS 是如何级联的……在网络上有比我更好的资源——

https://developer.mozilla.org/en-US/docs/Learn/CSS/Introduction_to_CSS/Cascade_and_inheritance

在我的示例片段中,我冒昧地制作了一个 JQuery 处理程序,以便文本输入字段知道它何时被填充,并在 keyup 上为其自身添加(或删除)一个填充类——你应该在某个地方为此添加一个处理程序,除非一个已经在您的代码中的某处触发(我猜您已经这样做了)。

我将这些类组合添加到 CSS,这样它们就不会以红色突出显示(在截图中样式表的底部)。

您使用的是 border-color,但您想要覆盖的实际属性在 CSS 中是简写的,所以我将它们切换为简写,并保证会影响相同的属性。我不记得它是如何运作的,但这可能是个问题......

$( "input[type=text]" ).keyup(function() {
if(this.value != '') $(this).addClass('filled');
else
$(this).removeClass('filled')
});

$("form").submit(function(){
var $requiredUnfilledItems = $('.required:not(.filled)');
if ($requiredUnfilledItems.length > 0)
{$requiredUnfilledItems.each( function(){$(this).addClass('warning-border');
});
}
else { alert("You entered in " + this.name.value); }
return false;})
.warning-border { 
outline: none !important;
border: thin solid red;
box-shadow: 0 0 10px red;
}

.warning-border, .select2-container.warning-border {
outline: none !important;
border: thin solid red;
box-shadow: 0 0 10px red;
}

.warning-border.filled, .select2-container--default .select2-selection--single {
width: 100%;
padding-left: 4px;
height: 100%;
border: thin solid lightgray;
height: 30px;
box-shadow: none;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form action="#" onsubmit="">
<input id="name" type="text" class="required filled" value="Name"/>
<input type="submit">
</form>

关于jquery - 如何以编程方式覆盖表单提交上的 select2 css?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54430785/

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