萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網頁製作 >> 互動設計

基於 jQuery 的圖片點擊放大、旋轉、新窗口打開完整效果

新浪微博、騰訊微博同款圖片查看體驗:點擊縮圖彈出大圖,支援左右旋轉、收起、新窗口打開。本文提供完整 jQuery 實現,開箱即用。

HTML 結構

<a class="miniImg artZoom" href="large.jpg">
  <img src="thumb.jpg" alt="Zoom" />
</a>

核心 jQuery 邏輯(節選關鍵流程)

$(function() {
  var imgID = 0;
  $('a.artZoom').click(function() {
    var id = $(this).attr('rel') || (++imgID);
    $(this).attr({id: 'artZoomLink-' + id, rel: id});

    var url = $(this).attr('href');
    $(this).append('<div class="loading" title="loading.."></div>');

    // 圖片預載
    var img = new Image();
    img.src = url;
    var loadFn = function() {
      $('#artZoomLink-' + id + ' .loading').remove();
      $('#artZoomLink-' + id).hide();

      if (!$('#artZoomBox-' + id).length) {
        var html = '<div class="artZoomBox" id="artZoomBox-' + id + '" style="display:none">';
        html += '<div class="tool">';
        html += '<a class="hideImg" href="#" rel="' + id + '">收起</a>';
        html += '<a class="imgLeft" href="#" rel="' + id + '">向左轉</a>';
        html += '<a class="imgRight" href="#" rel="' + id + '">向右轉</a>';
        html += '<a class="viewImg" href="#" rel="' + id + '">新窗口打開</a>';
        html += '</div>';
        html += '<a href="' + url + '" class="maxImgLink" id="maxImgLink-' + id + '" rel="' + id + '">';
        html += '<img class="maxImg" width="' + this.width + '" height="' + this.height + '" id="maxImg-' + id + '" src="' + url + '" />';
        html += '</a></div>';
        $('#artZoomLink-' + id).after(html);
      }
      $('#artZoomBox-' + id).show('fast');
    };
    if (img.complete) loadFn.call(img);
    else img.onload = loadFn;

    return false;
  });

  // 工具欄事件代理
  $('.artZoomBox a').live('click', function() {
    var id = $(this).attr('rel');
    if ($(this).is('.hideImg, .maxImgLink')) {
      $('#artZoomBox-' + id).hide('fast', function() { $('#artZoomLink-' + id).show(); });
    } else if ($(this).is('.imgLeft')) {
      $('#maxImg-' + id).rotateLeft(90); // 需旋轉插件支援
    } else if ($(this).is('.imgRight')) {
      $('#maxImg-' + id).rotateRight(90);
    } else if ($(this).is('.viewImg')) {
      window.open($('#maxImgLink-' + id).attr('href'));
    }
    return false;
  });
});

關鍵依賴

  • jQuery 核心庫
  • jQuery Rotate 插件(提供 .rotateLeft()/.rotateRight())

IE8 相容處理

旋轉後寬高互換可能導致容器高度塌陷,代碼中 IE8height(id) 函數動態補正容器高度。

效果預覽

Formee 示例

完整代碼含 CSS 樣式,可直接整合至專案,打造專業級圖片查看體驗。

copyright © 萬盛學電腦網 all rights reserved