gpt4 book ai didi

jquery - 使用 jquery 更改 css 文件不起作用

转载 作者:太空宇宙 更新时间:2023-11-04 00:53:51 24 4
gpt4 key购买 nike

我已经在堆栈溢出和网络上进行了搜索,但我找不到这个问题的答案,至少我不明白。由于我对这个主题(jquery 和 java)的了解有限。所以基本上我想在某些功能发生后更改其中一个 css 类 (#navbar a)。

我试图在脚本中实现它,但没有成功:

$('link[href="Style.css"]').addClass('#navbar a').css('width', '20px');

这是 javascript/jQuery:

<script>
window.onscroll = function() {myFunction()};

var navbar = document.getElementById("navbar");
var sticky = navbar.offsetTop;

function myFunction() {
if (window.pageYOffset >= sticky) {
navbar.classList.add("sticky")
navbar.style.align = 'auto';
navbar.style.width = '100%';
$('link[href="Style.css"]').addClass('#navbar a').css('width', '20px');
} else {
navbar.classList.remove("sticky");
navbar.style.width = '80%';
}
}
</script>

这是 css 文件/样式文件:

#navbar a {
float: left;
display: block;
color: #f2f2f2;
text-align: center;
width: 25%;
text-decoration: none;
font-size: 35px;
padding: 20px 0px;
}

这是整个 html 代码:

<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width;initial-scale=1;height=device">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<link rel="stylesheet" href="Style.css">
</head>
<body style="background:#101010">
<div class="header">
<h2>FELLE</h2>
</div>
<div id="navbar">
<a class="active" href="">Hjem</a>
<a href="Historie.html">Historie</a>
<a href="Hyttefelt.html">Hyttefelt</a>
<a href="Annet.html">Annet</a>
</div>
<div class="container" align="middle">
<img src="Bilder/Felle_Butikk.jpg" alt="Felle butikk"/>
<object data="Tekster/Felle_Butikk.txt"></object>
<img src="Bilder/Solhomfjell.jpg" alt="Solhomfjell i nissedal"/>
<object data="Tekster/Solhomfjell.txt"></object>
</div>

<script>
window.onscroll = function() {myFunction()};

var navbar = document.getElementById("navbar");
var sticky = navbar.offsetTop;

function myFunction() {
if (window.pageYOffset >= sticky) {
navbar.classList.add("sticky")
navbar.style.align = 'auto';
navbar.style.width = '100%';
$('link[href="Style.css"]').addClass('#navbar a').css('width', '20px');
} else {
navbar.classList.remove("sticky");
navbar.style.width = '80%';
}
}
</script>
</body>
</html>

最佳答案

$('link[href="Style.css"]').addClass('#navbar a').css('width', '20px');
<link href="Style.css" rel="stylesheet">
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

您有上面的代码,但这并没有修改样式表。它修改链接元素。

DOM screenshot

因为元素一开始是不可见的,所以给它一个宽度没有效果。


您可以修改实际元素的 style 属性(并完全包含样式表):

jQuery('#navbar a').css('width', '20px');

或者你可以 see this question关于更改 CSS 规则本身。

关于jquery - 使用 jquery 更改 css 文件不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55258151/

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