[英]How to make a div expand (by sliding outwards) in width on mouse click
我希望div從其當前寬度(400px)到特定指定寬度點擊時向右擴展。 (div將照片作為背景,因此最終結果寬度在每種情況下都會有所不同,但在大多數情況下大約為1000px)。
我怎么能用jquery / javascipt做到這一點? 謝謝
具有定義的寬度:
$(".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");
}
使用Jquery
<div id="box">Click me to grow</div>
<script>
$("#box").one( "click", function () {
$( this ).css( "width","+=200" );
});
</script>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.