Programing

jQuery로 DIV 배경 이미지 전환

lottogame 2020. 5. 8. 08:13
반응형

jQuery로 DIV 배경 이미지 전환


내가 일하는 회사의 확장 / 축소 통화 요금표를 만들고 있습니다. 현재 확장 할 수있는 버튼이있는 테이블이 있는데 버튼에 "확장"이라고 표시되어 있습니다. 버튼을 클릭 할 때 "Collapse"로 변경 한 다음 다시 클릭하면 "Expand"로 다시 돌아가는 버튼을 제외하고는 작동합니다. 버튼의 글은 배경 이미지입니다.

따라서 기본적으로 필요한 것은 전환과 같은 것을 제외하고 클릭 할 때 div의 배경 이미지를 변경하는 것입니다.


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

트릭을 수행하려면 요소의 클릭 이벤트에 연결하십시오.

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

개인적으로 JavaScript 코드를 사용하여 두 클래스 사이를 전환하려고합니다.

CSS에서 div에 필요한 모든 것을 배경 규칙으로 요약 한 다음 올바른 배경 이미지 (또는 스프라이트를 사용하는 경우 배경 위치)가있는 규칙으로 두 개의 클래스 (예 : 확장 및 축소)를 추가하십시오.

다른 이미지를 가진 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;}

또는 이미지 스프라이트가있는 CSS

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

.expanded {background-position: left bottom;}

그때...

이미지가 포함 된 JavaScript 코드

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

스프라이트가있는 JavaScript

참고 : 우아한 toggleClass는 Internet Explorer 6에서 작동하지 않지만 이 상황에서도 아래 addClass/ removeClass메소드가 제대로 작동합니다.

가장 우아한 솔루션

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

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

내가 아는 한이 방법은 브라우저에서 작동하며 스크립트의 URL 변경보다 CSS와 클래스를 사용하는 것이 훨씬 편안합니다.


jQuery를 사용하여 배경 이미지 CSS를 변경하는 방법에는 두 가지가 있습니다.

  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.


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


Here is how I do it:

CSS

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

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

JS

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

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:

$(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>

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.

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

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

<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>

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)
    });    
});

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.

$(".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);
                }
            }
        );

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).

$.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');
  });

});

I've found a solution in a forum, Toggle Background Img.


CSS Sprites work best. I tried switching classes and manipulating the 'background-image' property with jQuery, none worked. I think it's because the browsers (at least the latest stable Chrome) can't "reload" an image already loaded.

Bonus : CSS Sprites are faster to download and faster to display. Less HTTP requests means faster page load. Reducing the number of HTTP is the best way to improve front end performance, so I recommend going this route all the time.


This is a fairly simple response changes the background of the site with a list of items

function randomToN(maxVal) {
    var randVal = Math.random() * maxVal;
    return typeof 0 == 'undefined' ? Math.round(randVal) : randVal.toFixed(0);
};
var list = [ "IMG0.EXT", "IMG2.EXT","IMG3.EXT" ], // Images
    ram = list[parseFloat(randomToN(list.length))], // Random 1 to n
    img = ram == undefined || ram == null ? list[0] : ram; // Detect null
$("div#ID").css("backgroundImage", "url(" + img + ")"); // push de background

참고URL : https://stackoverflow.com/questions/253689/switching-a-div-background-image-with-jquery

반응형