本文介绍了使用if / else切换/更改Jquery中CSS的背景图像的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

花了好几个小时
请帮助

Been at it for hoursPlease help

   $("#NewsReel").click(function(){
   if( $(".block_news").css("background","url('/new_skool/images/news_1.jpg')no-repeat"))
   {
   $(".block_news").css("background","url('/new_skool/images/news(2).jpg')no-repeat");
   }
   else
   {
   if( $(".block_news").css("background","url('/new_skool/images/news(2).jpg')no-repeat"))
   {
   $(".block_news").css("background","url('/new_skool/images/news_1.jpg')no-repeat");
   }
   }
   });

谢谢

更改图片一次,但不会触发第二个if语句。

It changes the image once, but then does not fire the second if statement.

推荐答案

获取背景值不是这样的。您需要使用:

Getting the background value is not performed this way. You need to use:

if ($('element').css('background') == 'value') {
   ...
}

此外,我们无法保证jQuery不会完全按照您设置它的方式优化或设置背景。例如,它可能会返回以下值:

Also, there is is no guarantee that jQuery will not optimise or set the background exactly the way in which you set it. For example it might return the value as:

no-repeat url('/new_skool/images/news(2).jpg')

最好创建两个CSS类,只需使用更改背景图片,例如

It's best to create two CSS classes and just use toggleClass() to change the background image for example in this demo

<ul id="NewsReel">
    <li class="block_news">news</li>
</ul>​



CSS



CSS

li {
   background:url('http://lorempixel.com/25/25/abstract/1/') no-repeat;
}

li.clicked {
    background:url('http://lorempixel.com/25/25/abstract/2/') no-repeat;
}



JavaScript(jQuery)



JavaScript (jQuery)

$("#NewsReel").click(function() {
    $('.block_news').toggleClass('clicked');
    return false;
});

这篇关于使用if / else切换/更改Jquery中CSS的背景图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-15 05:18