Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
385 views
in Technique[技术] by (71.8m points)

javascript - 根据其他元素状态/类有条件地向元素添加类(Conditionally add class to element based on other element status/class)

I'm trying to hide an image after I scroll down my page.(向下滚动页面后,我试图隐藏图像。)

When scrolling my header gets a class fl-theme-builder-header-scrolled .(滚动时,我的header会得到一个fl-theme-builder-header-scrolled 。) My image div has a class hiding-image and I want to add a class image-off when the fl-theme-builder-header-scrolled class shows up in the header .(我的图像div有一个hiding-image类类image-offfl-theme-builder-header-scrolled类出现在header时,我想添加一个类image-off 。) This is what I have:(这就是我所拥有的:) $(document).ready(function() { if($( 'header' ).hasClass( 'fl-theme-builder-header-scrolled' )) { $( '.hiding-image' ).toggleClass( 'image-off' ); } }); but this doesn't work.(但这不起作用。) Any advice?(有什么建议吗?) Thx.(谢谢。)   ask by Chris Osiak translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Your code only runs once after the document ready, as soon as the page loads.(页面加载后,您的代码仅在文档准备好后运行一次。)

So if the header doesn't have the fl-theme-builder-header-scrolled class and only gets added later, your code will not run again.(因此,如果标头没有fl-theme-builder-header-scrolled类,并且仅在以后添加,则您的代码将不会再次运行。) You need aa mutation Observer.(您需要一个突变观察者。) Check this thread: Event trigger on a class change(检查此线程: 类更改时的事件触发器) Alternatively you can do as @Brewal is saying, putting the code evaluation on the scroll event.(另外,您也可以按照@Brewal所说的那样,将代码评估放在scroll事件上。) Although be careful so you don't run the code every time the scroll event is triggered since it can slow your website performance, specially on mobile devices.(尽管要小心,以免您每次触发滚动事件时都不要运行代码,因为这会降低网站的性能,特别是在移动设备上。)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

56.8k users

...