gpt4 book ai didi

javascript - 仅在特定主体类上使用 jQuery 应用 CSS

转载 作者:太空宇宙 更新时间:2023-11-03 21:03:54 24 4
gpt4 key购买 nike

WordPress 顶部导航菜单被 Logo 元素推得有点偏右了。我想做的是在页面加载时获得 Logo 宽度,并在菜单中添加负左边距,设置为 Logo 宽度的一半。我通过应用以下内容成功地做到了这一点:

jQuery(document).ready(function($){
var logoWidth = $('img#logo').width();
var logoWidthMargin = logoWidth / 2;
$('nav#top-menu-nav').css("margin-left", - logoWidthMargin);

});

这是 HTML:

<body class="some-class1 some-class2 some-class3">
<div id="page-container">
<header id="main-header">
<div class="container">
<div class="logo_container">
<img src="logo.png" id="logo"/>
</div>
<div id="top-navigation">
<nav id="top-menu-nav">
<ul id="top-menu" class="nav">
<li id="menu-item">Menu Item</li>
<li id="menu-item">Menu Item</li>
<li id="menu-item">Menu Item</li>
</ul>
</nav>
</div>
</div>
</header>
</div>
</body>

现在的问题是,我希望能够在特定页面上禁用它。 body 标签有多个类,我想以某种方式做到这一点,以便在 body 标签具有特定类的页面上,该脚本不会运行。

例如 - 我希望脚本像现在一样在所有页面上继续运行 - 但是一旦有一个页面的 body 标签有“some-class2”(除了其他类),脚本就赢了跑。我该怎么做?

另外 - 奖金问题 - 我对 js 和 jquery 很陌生,并且通过反复试验编写上面的代码直到它起作用,但是有没有更有效的方法来实现同样的目标?我的意思是,整个定义一个变量来获取 Logo 的宽度,然后定义另一个变量来获取该宽度的一半似乎有点过分,我确定有一个更短的方法我无法弄清楚.. .?

最佳答案

Now the thing is, I want to be able to disable this on specific pages. The body tag has multiple classes, and I'd like to somehow make it so that on a page in which the body tag has a certain class, this script will not run.

检查类(class):

if (!$("body").hasClass("the-class")) {
// run the script
}

现场:

jQuery(document).ready(function($){
if (!$("body").hasClass("the-class")) {
var logoWidth = $('img#logo').width();
var logoWidthMargin = logoWidth / 2;
$('nav#top-menu-nav').css("margin-left", - logoWidthMargin);
}
});

如果 Logo 的宽度已知(如果您查看它的 CSS,它可能确实如此),您也可以仅使用 CSS 来完成此操作:

body:not(.the-class) #top-menu-nav {
margin-left: -32px; /* Assuming the logo is 64px wide */
}

关于javascript - 仅在特定主体类上使用 jQuery 应用 CSS,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55990329/

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