2016-09-27 86 views
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); 
+1

如果你想居中背景圖像,你應該給它一個「背景位置」。對x軸和y軸都使用關鍵字'center'。 EG:簡寫形式將是'background:url(「imagePath」)center center no-repeat;'(參見:http://jsfiddle.net/k3ugj74e/5/) – Moob

+0

@moob謝謝你,工作。 – user713813

回答

0

此代碼總是適用於後我:

$('#yourimage').css({'top':'50%','left':'50%','margin':'-'+($('#yourimage').height()/2)+'px 0 0 -'+($('#yourimage').width()/2)+'px'}); 
0

背景圖像不會自動給你的DIV的寬度和高度,你必須手動設置您的中心功能工作。

還,您將div's母公司的背景,而不是在div本身,而you're試圖中心的空div,這顯然是不可見的效果