使用 jQuery 切换 DIV 背景图像

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/253689/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 08:50:14  来源:igfitidea点击:

Switching a DIV background image with jQuery

jquery

提问by zuk1

I am making an expand/collapse call rates table for the company I work for. I currently have a table with a button under it to expand it, the button says "Expand". It is functional except I need the button to change to "Collapse" when it is clicked and then of course back to "Expand" when it is clicked again. The writing on the button is a background image.

我正在为我工​​作的公司制作展开/折叠通话费率表。我目前有一张桌子,下面有一个按钮可以展开它,按钮上写着“展开”。它是有用的,除了我需要按钮在单击时更改为“折叠”,然后在再次单击时返回“展开”。按钮上的文字是背景图像。

So basically all I need is to change the background image of a div when it is clicked, except sort of like a toggle.

所以基本上我需要的只是在点击时更改 div 的背景图像,除了有点像切换。

回答by Nick

$('#divID').css("background-image", "url(/myimage.jpg)");  

Should do the trick, just hook it up in a click event on the element

应该可以解决问题,只需将其连接到元素上的点击事件中

$('#divID').click(function()
{
  // do my image switching logic here.
});

回答by Kelly

I personally would just use the JavaScript code to switch between 2 classes.

我个人只会使用 JavaScript 代码在 2 个类之间切换。

Have the CSS outline everything you need on your div MINUS the background rule, then add two classes (e.g: expanded & collapsed) as rules each with the correct background image (or background position if using a sprite).

让 CSS 在 div 上勾勒出您需要的所有内容减去背景规则,然后添加两个类(例如:展开和折叠)作为规则,每个类都具有正确的背景图像(如果使用精灵,则为背景位置)。

CSS with different images

具有不同图像的 CSS

.div {
    /* button size etc properties */
}

.expanded {background: url(img/x.gif) no-repeat left top;}
.collapsed {background: url(img/y.gif) no-repeat left top;}

Or CSS with image sprite

带有图像精灵的 CSS

.div {
    background: url(img/sprite.gif) no-repeat left top;
    /* Other styles */
}

.expanded {background-position: left bottom;}

Then...

然后...

JavaScript code with images

带有图像的 JavaScript 代码

$(function){
    $('#button').click(function(){
        if($(this).hasClass('expanded'))
        {
            $(this).addClass('collapsed').removeClass('expanded');
        }
        else
        {
            $(this).addClass('expanded').removeClass('collapsed');
        }
    });
}

JavaScript with sprite

带有精灵的 JavaScript

Note: the elegant toggleClass does not work in Internet Explorer 6, but the below addClass/removeClassmethod will work fine in this situation as well

注意:优雅的 toggleClass 在 Internet Explorer 6 中不起作用,但下面的addClass/removeClass方法在这种情况下也能正常工作

The most elegant solution (unfortunately not Internet Explorer 6 friendly)

最优雅的解决方案(遗憾的是 Internet Explorer 6 不友好)

$(function){
        $('#button').click(function(){
            $(this).toggleClass('expanded');
        });
    }

$(function){
        $('#button').click(function(){
            if($(this).hasClass('expanded'))
            {
                $(this).removeClass('expanded');
            }
            else
            {
                $(this).addClass('expanded');
            }
        });
    }

As far as I know this method will work accross browsers, and I would feel much more comfortable playing with CSS and classes than with URL changes in the script.

据我所知,这种方法可以跨浏览器工作,而且我会觉得使用 CSS 和类比在脚本中更改 URL 更舒服。

回答by Ecropolis

There are two different ways to change a background image CSS with jQuery.

有两种不同的方法可以使用 jQuery 更改背景图像 CSS。

  1. $('selector').css('backgroundImage','url(images/example.jpg)');
  2. $('selector').css({'background-image':'url(images/example.jpg)'});
  1. $('selector').css('backgroundImage','url(images/example.jpg)');
  2. $('selector').css({'background-image':'url(images/example.jpg)'});

Look carefully to note the differences. In the second, you can use conventional CSS and string multiple CSS properties together.

仔细观察以注意差异。在第二种情况下,您可以使用传统的 CSS 并将多个 CSS 属性串在一起。

回答by Dave Ward

If you use a CSS sprite for the background images, you could bump the background offset +/- npixels depending on whether you were expanding or collapsing. Not a toggle, but closer to it than having to switch background image URLs.

如果您对背景图像使用 CSS 精灵,您可以根据您是展开还是折叠来将背景偏移量增加 +/- n像素。不是切换,而是比切换背景图片 URL 更接近它。

回答by Loupax

Here is how I do it:

这是我如何做到的:

CSS

CSS

#button{
   background-image: url("initial_image.png");
}

#button.toggled{
  background-image:url("toggled_image.png");
}

JS

JS

$('#button').click(function(){
  $('#my_content').toggle();
  $(this).toggleClass('toggled');
});

回答by alexp206

One way to do this is to put both images in the HTML, inside a SPAN or DIV, you can hide the default either with CSS, or with JS on page load. Then you can toggle on click. Here is a similar example I am using to put left/down icons on a list:

一种方法是将两个图像都放在 HTML 中,在 SPAN 或 DIV 中,您可以在页面加载时使用 CSS 或 JS 隐藏默认值。然后你可以点击切换。这是我用来将左/下图标放在列表中的类似示例:

$(document).ready(function(){
    $(".button").click(function () {
        $(this).children(".arrow").toggle();
            return false;
    });
});

<a href="#" class="button">
    <span class="arrow">
        <img src="/images/icons/left.png" alt="+" />
    </span>
    <span class="arrow" style="display: none;">
        <img src="/images/down.png" alt="-" />
    </span>
</a>

回答by enobrev

This works on all current browsers on WinXP. Basically just checking what the current backgrond image is. If it's image1, show image2, otherwise show image1.

这适用于 WinXP 上的所有当前浏览器。基本上只是检查当前的背景图像是什么。如果是image1,显示image2,否则显示image1。

The jsapi stuff just loads jQuery from the Google CDN (easier for testing a misc file on the desktop).

jsapi 的东西只是从 Google CDN 加载 jQuery(更容易在桌面上测试 misc 文件)。

The replace is for cross-browser compatibility (opera and ie add quotes to the url and firefox, chrome and safari remove quotes).

替换是为了跨浏览器兼容性(opera 和 ie 添加引号到 url 和 firefox、chrome 和 safari 删除引号)。

<html>
    <head>
        <script src="http://www.google.com/jsapi"></script>
        <script>
          google.load("jquery", "1.2.6");
          google.setOnLoadCallback(function() {
            var original_image = 'url(http://stackoverflow.com/Content/img/wmd/link.png)';
            var second_image = 'url(http://stackoverflow.com/Content/img/wmd/code.png)';

            $('.mydiv').click(function() {
                if ($(this).css('background-image').replace(/"/g, '') == original_image) {
                    $(this).css('background-image', second_image);
                } else {
                    $(this).css('background-image', original_image);
                }

                return false;
            });
          });
        </script>

        <style>
            .mydiv {
                background-image: url('http://stackoverflow.com/Content/img/wmd/link.png');
                width: 100px;
                height: 100px;
            }
        </style>
    </head>
    <body>
        <div class="mydiv">&nbsp;</div>
    </body>
</html>

回答by yPhil

Mine is animated:

我的是动画:

$(this).animate({
    opacity: 0
}, 100, function() {
    // Callback
    $(this).css("background-image", "url(" + new_img + ")").promise().done(function(){
        // Callback of the callback :)
        $(this).animate({
            opacity: 1
        }, 600)
    });    
});

回答by user2220104

I did mine using regular expressions, since I wanted to preserve a relative path and not use add the addClass function. I just wanted to make it convoluted, lol.

我使用正则表达式做了我的,因为我想保留一个相对路径而不是使用 addClass 函数。我只是想让它变得复杂,哈哈。

$(".travelinfo-btn").click(
            function() {
                $("html, body").animate({scrollTop: $(this).offset().top}, 200);
                var bgImg = $(this).css('background-image')
                var bgPath = bgImg.substr(0, bgImg.lastIndexOf('/')+1)
                if(bgImg.match(/collapse/)) {
                    $(this).stop().css('background-image', bgImg.replace(/collapse/,'expand'));
                    $(this).next(".travelinfo-item").stop().slideToggle(400);
                } else {
                    $(this).stop().css('background-image', bgImg.replace(/expand/,'collapse'));
                    $(this).next(".travelinfo-item").stop().slideToggle(400);
                }
            }
        );

回答by bphillips

Old post, but this would allow you to use an image sprite and adjust the repeat as well as positioning by using the shorthand for the css property (background, repeat, left top).

旧帖子,但这将允许您使用图像精灵并通过使用 css 属性(背景、重复、左上角)的简写来调整重复和定位。

$.each($('.smallPreview'), function(i){
  var $this = $(this);

  $this.mouseenter(function(){
    $this.css('background', 'url(Assets/imgs/imgBckg-Small_Over.png) no-repeat 0 0');
  });

  $this.mouseleave(function(){
    $this.css('background', 'url(Assets/imgs/imgBckg-Small.png) no-repeat 0 0');
  });

});