2014-01-20 36 views
0

jsFiddlejQuery如何垂直和水平中心圖像a.k.a.圖像燈箱?

$(document).ready (function(){ 
    $("a").click(function(){ 
      $(".myCanvas").fadeIn(); 
      $(".myCanvas").html ($(this).html());    
    }); 
}); 

a是一個圖像鏈接。是否可以在$(this.html)內放置$(this).css({});?我想要做的是當我點擊圖像時,我希望圖像出現在網頁中間,背後有一個透明的黑色背景,以便在不使用Fancybox和lightbox的情況下覆蓋其他圖像。

回答

2

在這裏你去瞧一瞧:

http://jsfiddle.net/mattdlockyer/SyJSS/1/

CSS:

#img-container { 
    position:fixed; 
    display:none; 
    top:50%; 
    left:50%; 
    margin-top:-50px; 
    margin-left:-100px; 
    z-index:9999; 
} 

JS:

$('.img').on('click', function (e) { 
    $('#img-cover').fadeIn(); 
    var img = $(this); 
    $('#img-container').html(img.clone()) 
     .css({ 
     'margin-top': '-' + img.height()/2 + 'px', 
      'margin-left': '-' + img.width()/2 + 'px' 
    }).fadeIn(); 
}); 

$('#img-cover').on('click', function() { 
    $('#img-cover').fadeOut(); 
    $('#img-container').fadeOut(); 
}); 

來源:http://css-tricks.com/quick-css-trick-how-to-center-an-object-exactly-in-the-center/

意見:使用庫。通常有一些輕量級的應用程序會考慮瀏覽器的兼容性。隨時推出自己的解決方案是一種痛苦。

+0

先生,你如何使它不會從背頁消失。我嘗試了使用2個圖像。每當我點擊圖片,它就會從網站上消失,並顯示在中間。謝謝 – user1998735

+0

更新的小提琴和代碼,這應該做你想找的。請接受我的標題編輯,因爲它使問題更清晰,解決方案更有價值。 – mattdlockyer

+0

非常謝謝你,馬特先生。它現在的作品... – user1998735

0

Here是一個解決方案的小提琴。點擊一個圖像(彩色塊)打開myCanvas並填充選定的圖像。點擊myCanvas中的任意位置將其隱藏並選擇其他圖片。

HTML:

<div id="wrapper"> 
    <div class="images_box"> 
     <a><img style="background: red;" /></a> 
     <a><img style="background: blue;" /></a> 
     <a><img style="background: green;" /></a> 
     <a><img style="background: black;" /></a> 
     <a><img style="background: pink;" /></a> 
    </div> 
    <div class="myCanvas"></div> 
</div> 

CSS:

* { 
    padding: 0px; 
    margin: 0px; 
} 
#wrapper { 
    position: relative; 
    width: 80%; 
    margin-right: auto; 
    margin-left: auto; 
    height: 300px; 
    /*background: #123;*/ 
} 
.images_box { 
    width: 100%; 
    height: 60px; 
} 
img { 
    display: inline-block; 
    height: 50px; 
    width: 50px; 
    margin: 0px; 
    padding: 5px; 
} 
.myCanvas { 
    display: none; 
    width: 100%; 
    height: 300px; 
    position: absolute; 
    top: 0px; 
    left: 0px; 
    background: #999; 
} 

的JavaScript:

$(document).ready(function() { 
    $('a').click(function() { 
     $('.myCanvas').fadeIn(); 
     $('.myCanvas').html($(this).html()); 
     $('.myCanvas').children().css('display', 'block'); 
     $('.myCanvas').children().css({ 
      'margin-left': 'auto', 
      'margin-right': 'auto' 
     }); 

     var topMargin = 125; 

     $('.myCanvas').children().css('margin-top', topMargin); 
    }); 

    $('.myCanvas').click(function() { 
     $('.myCanvas').fadeOut(); 
    }); 
}); 

它採用圖像(將html複製到myCanvas)然後居中。

+0

這是一個很大的CSS,並假定固定的寬度和高度...... – mattdlockyer

+0

這只是一個例子,你可以把所有的寬度和高度,並改變它們,或修改腳本,使他們充滿活力。這只是一個概念證明。而只有硬值爲'topMargin'在JS代碼,並可以很容易地修改,從DIV的寬度和高度來計算的動態值。 – Birrel

+0

權,只是一個評論,但它運作良好。 – mattdlockyer