完全重做了解決方案:http://jsfiddle.net/02asmj4w/15/ 爲什麼?因爲我有一些在清晨擺弄迫切需要...
什麼呢我的解決方法做: - 它的水平和垂直居中點擊框視口內部
我做了什麼: - 每一個div的現在有另外一個id去上課。
類CSS看起來如下
。col {height:100px; height:100px; width:100px; float:left; margin-left:10px; margin-top:5px; position:absolute; top:0px; }
的ID CSS只是設置每個div的左側位置,並設置一些不同的背景顏色,以更好地區分箱
DIV3 {
left: 220px;
background: #cde;
}
好的...那只是造型thingies,這裏沒什麼特別的... 現在爲js:
var leftOffset; //declare a global variable leftOffset for later usage
$('.col').click(function() { // on click
if (!$(this).hasClass("clicked")) { // if clicked div is not the centered one
// get viewport dimensions and set needed margins
var currentViewPortWidth = $(window).width();
var currentViewPortHeight = $(window).height();
var marginLR = (currentViewPortWidth - 250)/2;
var marginTB = (currentViewPortHeight - 250)/2;
leftOffset = $(this).css("left"); // store clicked div left offset in global var
$(".clicked").animate({ // define the 'go back to initial pos' animation
width: '100px',
height: '100px',
left: leftOffset,
marginLeft: '10px',
marginTop: '5px'
}).removeClass("clicked"); // remove 'clicked' class handler
$(this).animate({ // define 'clicked div go to center' animation
width: '250px',
height: '250px',
left: '0px',
marginLeft: marginLR,
marginTop: marginTB
}).addClass("clicked"); // set clicked class handler
} else { // else means: clicked div is the centered one
$(this).animate({ // define the 'go back to initial pos' animation
width: '100px',
height: '100px',
left: leftOffset,
marginLeft: '10px',
marginTop: '5px'
}).removeClass("clicked");
}
});
// ensure, that the div stays centered on window resize
$(window).resize(function() {
var currentViewPortWidth = $(window).width();
var currentViewPortHeight = $(window).height();
var marginLR = (currentViewPortWidth - 250)/2;
var marginTB = (currentViewPortHeight - 250)/2;
$('.clicked').css({"margin-left": marginLR, "margin-top": marginTB});
});
但仍然不是在中心,而是在您的更新小提琴。 – 2014-09-11 11:50:40
@Maddy第一個'div'只能用,對。爲了避免所有這些亂用'div's你可以隱藏所有其他'div'。你能接受嗎? – Regent 2014-09-11 12:01:05
@Maddy否則,可以使用'$(this).css(「position」,「absolute」);'來定位元素。 – Regent 2014-09-11 12:03:43