Hãy đăng ký thành viên để có thể dễ dàng trao đổi, giao lưu và chia sẻ về kiến thức đồ họa.
  1. Hãy đăng ký subscribe kênh Youtube mới của Việt Designer tại địa chỉ: Youtube.com/VietDesignerChannel để theo dõi các video về thiết kế đồ họa. Do trước đó kênh cũ bị Youtube quét không rõ lý do, trong thời gian chờ kháng cáo nếu các bạn thấy video trên diễn đàn bị die không xem được thì có thể vào kênh mới để tìm xem video sơ cua nhé.
    Loại bỏ thông báo

Tooltip cho hình ảnh sử dụng Javascript

Chủ đề thuộc danh mục 'HTML - CSS - JS - PHP - ASP' được đăng bởi TrollVL, 3/11/13.

Lượt xem: 11,431

  1. TrollVL Thành viên cấp 2

    Có rất nhiều cách để hiển thị tooltip cho hình ảnh, và ở bài viết này mình sẽ giới thiệu đến các bạn một dạng tooltip. Đặc biệt với hiệu ứng tooltip này, bạn sẽ không phải lo lắng về hình ảnh tooltip hiển thị quá xa so với hình ảnh thu nhỏ mà hình ảnh phóng to sẽ di chuyển theo con trỏ chuột. Đoạn javascript bên dưới sẽ giúp chúng ta trong công việc này

    [​IMG]

    Code:
    /*! JavaScript Image Trail 
    	
    Tooltip by Taufik Nurrohman <http://gplus.to/tovic> */
    (function(w, d) {
     
        var 
    	
    tooltip = d.createElement('div'),
            noImage = "data:image/gif;base64,R0lGODlhAQABAIAAAAAAA///yh5BAEAAAAALAAAAAABAAEAAAIBRAA7", // 1 x 1 pixel transparent GIF
            top = 0,
            left = 0,
            docWidth = 0,
            docHeight = 0,
            offsetTop = 20,// Default top distance of the 
    	
    tooltip to the mouse pointer
            offsetLeft = 20,// Default left distance of the 
    	
    tooltip to the mouse pointer
            wait = null;
     
      // Get the correct width of the document without scrollbars
        function getDocWidth() {
            return d.documentElement.clientWidth;
        }
     
      // Get the correct height of the document
        function getDocHeight() {
            return Math.max(
                d.body.scrollHeight, d.documentElement.scrollHeight,
                d.body.offsetHeight, d.documentElement.offsetHeight,
                d.body.clientHeight, d.documentElement.clientHeight
            );
        }
     
        
    	
    tooltip.id = "trail-image";
        
    	
    tooltip.className = "trail-image";
        
    	
    tooltip.innerHTML = '<img src="' + noImage + '" alt="Loading..." style="float:none;display:block;width:100%;height:100%;max-width:none;max-height:none;min-width:0;min-height:0;border:none;outline:none;background:none;margin:0;padding:0;">';
     
      // Just like `DOMContentLoaded` event, but only to
      // wait for the existence of the `<body>` element
      // to insert the 
    	
    tooltip markup in the proper area
        function waitForBodyExist() {
            if (!d.body) {
                wait = setTimeout(waitForBodyExist, 100);
            } else {
                clearTimeout(wait);
                d.body.appendChild(
    	
    tooltip);
                docWidth = getDocWidth();
                docHeight = getDocHeight();
                w.onresize = function() {
                    docWidth = getDocWidth();
                    docHeight = getDocHeight();
                };
                w.onscroll = hideTrail;
            }
          // console.log('Still waiting...');
        } waitForBodyExist();
     
      // Function to show the 
    	
    tooltip
      // `width`  => the 
    	
    tooltip width
      // `height` => the 
    	
    tooltip height
      // `file`  => the URL of the image to show
        function showTrail(width, height, file) {
            
    	
    tooltip.style.visibility = "visible";
            
    	
    tooltip.children[0].src = file;
            
    	
    tooltip.style.width = parseInt(width, 10) + "px";
            
    	
    tooltip.style.height = parseInt(height, 10) + "px";
            d.onmousemove = function(e) {
                if (!e) e = w.event;
                if (e.pageX || e.pageY) {
                    left = e.pageX;
                    top = e.pageY;
                } else if (e.clientX || e.clientY) {
                    left = e.clientX + d.body.scrollLeft + d.documentElement.scrollLeft;
                    top = e.clientY + d.body.scrollTop + d.documentElement.scrollTop;
                }
                
    	
    tooltip.style.top = parseInt(((top >= docHeight - (height + offsetTop + 10)) ? top - (height + offsetTop) : top + offsetTop), 10) + "px";
                
    	
    tooltip.style.left = parseInt(((left >= docWidth - (width + offsetLeft + 10)) ? left - (width + offsetLeft) : left + offsetLeft), 10) + "px";
            };
        }
     
      // Function to hide the 
    	
    tooltip
        function hideTrail() {
            d.onmousemove = "";
            
    	
    tooltip.style.top = "-9999px";
            
    	
    tooltip.style.left = "-9999px";
            
    	
    tooltip.style.visibility = "hidden";
            
    	
    tooltip.children[0].src = noImage;
            docWidth = getDocWidth();
            docHeight = getDocHeight();
        }
     
      // Add to the window object as an external/global function
        w.showTrail = showTrail;
        w.hideTrail = hideTrail;
     
    })(window, document);
    CSS
    Code:
    /* Image Trail 
    	
    Tooltip CSS */
    .trail-image {
      width:0;
      height:0;
      background-color:#ddd;
      border:1px solid #888;
      position:absolute;
      top:-9999px;
      left:-9999px;
      z-index:9999;
      visibility:hidden;
      -webkit-box-shadow:0 1px 1px rgba(0,0,0,.2);
      -moz-box-shadow:0 1px 1px rgba(0,0,0,.2);
      box-shadow:0 1px 1px rgba(0,0,0,.2);
    }


    Cách sử dụng cơ bản
    Có hai chức năng chính trong đoạn js bên trên, cụ thể là showTrail và hideTrail . showTrail được sử dụng để hiển thị một tooltip trong khi hideTrail được sử dụng để ẩn tooltip. Bạn có thể áp dụng nó vào thuộc tính onmouseover và onmouseout như sau:
    Code:
    <a href="img/large.jpg">
      <img onmouseover="showTrail(250, 100, &#39;img/medium.jpg&#39;);" onmouseout="hideTrail();" src="img/small.jpg" alt="">
    </a>
    • img/large.jpg: Link hình gốc
    • img/medium.jpg: Link hình ảnh tooltip (có thể lấy link ảnh gốc)
    • img/small.jpg: Link hình ảnh thu nhỏ
    • 250: Chiều rộng của hình ảnh tooltip
    • 100: Chiều cao của hình ảnh tooltip
    Demo
    Lưu dữ liệu trong các thuộc tính của HTML
    Nếu bạn thực hiện công việc này cho bài viết của blog/website của mình thường xuyên bạn nên làm theo cách sau và bạn sẽ không phải mất thời gian chỉnh sửa kích cỡ của từng hình ảnh tooltip nữa. Sử dụng cấu trúc HTML sau:
    Code:
    <img alt="" src="img/small.jpg" data-image-preview="img/medium.jpg">
    • img/small.jpg: Link hình ảnh thu nhỏ
    • img/medium.jpg: Link hình ảnh tooltip (có thể lấy link ảnh gốc)
    Sau đó bạn thêm đoạn JS sau để thực hiện cố định kích thước cho hình ảnh tooltip
    Code:
    (function() {
        var img = document.getElementsByTagName('img');
        for (var i = 0, len = img.length; i < len; ++i) {
            if (img[i].getAttribute('data-image-preview')) {
                img[i].onmouseover = function() {
                    showTrail(this.offsetWidth * 3, this.offsetHeight * 3, this.getAttribute('data-image-preview'));
                };
                img[i].onmouseout = hideTrail;
            }
        }
    })();
    Trong đoạn JS trên có 2 thông số là .offsetWidth * 3.offsetHeight * 3 nghĩa là hình ảnh tooltip sẽ lớn gấp 3 lần hình ảnh thu nhỏ.

    Demo
    Chúc các bạn thành công!

    ...
    yeucongviec, Phạm Hữu Dưbanbaonylong thích bài viết này.
  2. vudinh129

    vudinh129 Banned

    hình như ko chạy được bạn ơi
    aoyamt193boomer_daica01 thích bài viết này.
  3. TrollVL

    TrollVL Thành viên cấp 2

  4. chạy ổn mà bác, kiểm tra lại xem
    TrollVL thích bài viết này
  5. yeucongviec

    yeucongviec Banned

    hay lém thank u
  6. nhung_it

    nhung_it Mới đăng kí

    Bây h em muốn thêm một đoạn text bên dưới hình ảnh thì phải sửa code như thế nào ạ?
  7. NND

    NND Banned

    Mình muốn code nó tự động với tất cả các bài viết có được không bạn?
Từ khóa:

Ủng hộ diễn đàn