如何使用jQuery在一个元素上应用样式
在这篇文章中,我们将学习如何使用jQuery在一个元素上应用一个样式。假设你正在建立一个网站或游戏,你需要用户界面是互动的。在这种情况下,样式可以发挥巨大的作用,在这篇文章中,我们将学习如何在JQuery的帮助下在某些事件被触发时改变样式。我们可以通过使用JQuery CSS Classes或JQuery .css()方法在元素上应用样式。
方法1:使用JQuery CSS类。这种方法包括使用一些方法,如addClass()方法、removeClass()方法和toggleClass()方法。这些方法与classList.addClass()方法和classList.removeClass()方法类似。我们可以用一些css规则创建一些类,并根据需求使用JQuery添加或删除它们。
语法:
$("#poll").removeClass("safe").addClass("danger");
// OR
$("#poll").toggleClass("danger");
示例:
<!DOCTYPE html>
<html lang="en">
<head>
<script src=
"https://code.jquery.com/jquery-3.6.0.min.js">
</script>
<style>
#poll {
position: absolute;
bottom: 15%;
}
#submit {
position: absolute;
bottom: 10%;
}
.safe {
background-color: rgb(6, 161, 6);
width: 20%;
height: 30%;
}
.danger {
background-color: rgb(226, 19, 19);
width: 20%;
height: 60%;
}
</style>
</head>
<body>
<h1 style="color: green">GeeksforGeeks</h1>
<h3>How can you apply a style on an
element using jQuery?</h3>
<div id="poll" class="safe"></div>
<button id="submit">Alarm</button>
<script>
("#submit").click(function () {
// We can either remove the old
// class and add a new one
//("#poll").removeClass("safe").addClass("danger");
// Otherwise, we can toggle the class
$("#poll").toggleClass("danger");
})
</script>
</body>
</html>
输出:
在上面的例子中,我们为不同的状态维护了两个不同的类safe和danger。最初,安全类被附加到ID为#poll的DIV上,当点击按钮时,这个安全类被移除,危险类被动态添加,增加了DIV的高度并将其背景颜色改为红色。
如果你对删除哪个类和添加哪个类感到困惑,那么toggleClass(“className”)方法就是为你准备的。这个方法将类(在方法中作为参数传递)添加到HTML标签中,如果当前没有添加,或者将类从元素中移除,如果当前已经添加到HTML标签中。简单地说,这个方法在添加/删除选定元素的类之间进行切换。
方法2:使用JQuery css()方法:在这个方法中,你可以直接从javascript本身设置样式,而不是在样式表内创建单独的类。css()方法可以用来根据给定的属性返回一个单一的属性,或者设置一个或多个CSS属性。
语法:
// Assigning a single CSS property
("#phone").css("background", "red");
// Assigning multiple properties("#phone").css({"background": "red", "font-size": "16px"});
示例 2:
<!DOCTYPE html>
<html lang="en">
<head>
<script src=
"https://code.jquery.com/jquery-3.6.0.min.js">
</script>
</head>
<body>
<h1 style="color: green">GeeksforGeeks</h1>
<h3>How can you apply a style on an
element using jQuery?</h3>
<b>Telephone Number Verification</b>
<br><br>
<input type="number" id="phone"
placeholder="Enter the Phone No." />
<span id="warning"></span><br><br>
<button id="submit">Check</button>
<script>
("#submit").click(function () {
// Regular expression to check
// for an indian phone number
const regexExp = /^[6-9]\d{9}/gi;
const phone = ("#phone").val();
// Add or remove classes based on
// the regular expression check
if (!regexExp.test(phone)) {
("#warning").text("It's wrong try again!");
("#warning").css("color", "red");
("#phone").css("background", "red");
} else {
("#warning").text("It's correct");
("#warning").css("color", "green");
$("#phone").css("background", "green");
}
});
</script>
</body>
</html>
输出:我们已经检查了输入的印度电话号码是否正确,为此我们根据一个自定义的重码模式检查了输入值,如果是假的,那么我们使用JQuery CSS方法改变了输入文本区的背景颜色并显示了一个警告。