jQuery 是一个快速、小巧且功能丰富的 JavaScript 库,它简化了 HTML 文档遍历、事件处理、动画和 Ajax 交互。动态增加 CSS 样式是指在页面加载后,通过 JavaScript 或 jQuery 修改元素的样式属性。
style
属性。<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>jQuery 动态增加 CSS 样式</title>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<style>
.highlight {
background-color: yellow;
}
</style>
</head>
<body>
<button id="changeStyleBtn">改变样式</button>
<p id="text">这是一段文本。</p>
<script>
$(document).ready(function() {
$('#changeStyleBtn').click(function() {
$('#text').css('color', 'red');
});
});
</script>
</body>
</html>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>jQuery 动态增加 CSS 样式</title>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<style>
.highlight {
background-color: yellow;
}
</style>
</head>
<body>
<button id="changeClassBtn">改变类名</button>
<p id="text">这是一段文本。</p>
<script>
$(document).ready(function() {
$('#changeClassBtn').click(function() {
$('#text').addClass('highlight');
});
});
</script>
</body>
</html>
原因:
解决方法:
$(document).ready()
确保 DOM 加载完成后再执行脚本。$(document).ready(function() {
$('#changeStyleBtn').click(function() {
$('#text').css('color', 'red');
});
});
通过以上方法,可以有效地解决 jQuery 动态增加 CSS 样式时遇到的问题。
领取专属 10元无门槛券
手把手带您无忧上云