2011-11-25 29 views
0

我想要一個div從其當前寬度(400px)單擊展開到某個指定寬度。 (divs有照片作爲背景,因此最終結果寬度在每種情況下都會有所不同,但在大多數情況下大小約爲1000px)。如何在鼠標點擊時將寬度向外展開(向外滑動)

我該如何使用jquery/javascipt做到這一點?感謝

+0

試試這個問題:http://stackoverflow.com/questions/596608/jquery-slide-right-to-left – slapthelownote

回答

2

具有限定寬度:

$(".clickElement").click(function(){ 
    if($(this).is(".open")) 
    { 
     $(this).animate({ width: 400}, 500); 
    } 
    else 
    { 
     $(this).animate({ width: 1000}, 500); 
    } 
    $(this).toggleClass("open"); 
}); 

檢查圖像的寬度(背景):
見本小提琴:http://jsfiddle.net/4ZfsD/2/

function toggle() { 
    if ($(this).is(".open")) { 
     $(this).animate({ 
      width: 400 
     }, 500); 
    } 
    else { 
     $(this).animate({ 
      width: $(this).data("width") 
     }, 500); 
    } 
    $(this).toggleClass("open"); 
} 
$("#test").click(function() { 
    // No image width yet, we have to get it from the image 
    if (!$(this).data("width")) { 
     var img = new Image(); 
     var _this = $(this); 

     img.onload = function() { 
      // Image is loaded, save the width and call the toggle function 
      _this.data("width", this.width); 
      toggle.call(_this); 
     } 
     img.src = $(this).css("backgroundImage").replace("url(\"", "").replace("\")", ""); 
    } else { // We already got a width, just call toggle function 
     toggle.call(this); 
    } 
}); 

CSS:

#test 
{ 
    width: 400px; 
height: 400px; 
background-image:url("http://lokeshdhakar.com/projects/lightbox2/images/image-2.jpg"); 
} 
0

使用jQuery

<div id="box">Click me to grow</div> 

    <script> 
    $("#box").one("click", function() { 
    $(this).css("width","+=200"); 
    }); 
    </script>