1
我有一個將對齊功能添加到jquery的函數。 它適用於與文本div應用時發現。 但設置背景時不起作用。 我做錯了什麼?使用jquery在屏幕中心使用背景圖像居中div
這裏是一個小提琴演示 http://jsfiddle.net/k3ugj74e/
<div id='target'></div>
$.fn.center = function() {
this.css("position", "absolute");
this.css("top", Math.max(0, (($(window).height() - $(this).outerHeight())/2) + $(window).scrollTop()) + "px");
this.css("left", Math.max(0, (($(window).width() - $(this).outerWidth())/2) + $(window).scrollLeft()) + "px");
return this;
}
var i ='https://www.google.com/logos/doodles/2016/googles-18th-birthday-5661535679545344-hp.gif'
var backgroundimage = "url('" + i + "') no-repeat";
//this doesn't
$("#target").parent().css('background', backgroundimage);
//this works
//$("#target").text('hi');
$("#target").center(true);
如果你想居中背景圖像,你應該給它一個「背景位置」。對x軸和y軸都使用關鍵字'center'。 EG:簡寫形式將是'background:url(「imagePath」)center center no-repeat;'(參見:http://jsfiddle.net/k3ugj74e/5/) – Moob
@moob謝謝你,工作。 – user713813