2013-04-08 107 views
0

我需要在頁面上的所有圖像上添加透明圖像。目標是如果用戶要做一個簡單的右鍵單擊並保存圖像,他們會保存透明圖像。使用JavaScript在其他圖像上添加透明圖像

我確實意識到這不是一種有保證的方法,也不存在防止圖像被盜的方法,而只是客戶想要添加的一種方法,以防止普通非技術人員保存圖像。

  • 使用JavaScript我想查找某個分區內的所有圖像或所有圖像。
  • 應用這些圖像的頂部一個新的圖像疊加,將有圖像相同的寬度和高度,他們都覆蓋

我不知道如何用JavaScript做到這一點,希望有人將有一個快速修復或例子。 Google或SO目前無法找到任何內容。感謝所有幫助

我有這個JS其中一個網頁上獲得所有圖像到目前爲止...

// Get all images on a Page 
function checkimages() { 
    var images = document.images; 
    for (var i=0; i<images.length; i++){ 
     var img =images[i].src; 

     // Add new transparent image on top of this image 
     alert(img); 
    } 
} 

回答

2

我會建議你使用jQuery(或類似的庫)來保持簡單。我甚至會寫一個小的jquery擴展,以便輕鬆地回收代碼,並將其應用於任何div(或其他包裝器),您希望覆蓋的子圖像。

我的代碼看起來是這樣的:

// jquery plugin to create overlays 
// src is the url of the overlay image 
// apply to any container that contains images to be overlayed 
$.fn.overlayImages = function(src) { 
    // loop trough the images 
    $(this).find('img').each(function() { 
     // cache some variables 
     var $img = $(this); 
     var $parent = $img.parent(); 
     // make the parent relative, if not yet absolute or fixed, for easy positioning 
     if ($parent.css('position') !== 'fixed' && $parent.css('position') !== 'absolute') { 
      $parent.css('position', 'relative');    
     } 
     // get the position of the image 
     var position = $img.position(); 
     // clone the image 
     var $overlay = $img.clone(); 
     // set the styling, based on the img, for exact positioning 
     $overlay.css({ 
      top: position.top, 
      left: position.left, 
      position: 'absolute', 
      width: $img.width(), 
      height: $img.height() 
     }); 
     // change the src attribute for the overlay 
     $overlay.attr('src', src); 
     // insert the overlay to the DOM 
     $overlay.insertAfter($img); 
    }); 
} 

// when the DOM is loaded (not just ready, the images need to be there to copy their position and size) 
$(window).load(function() { 
    // apply the overlay plugin to the wrapper of the images 
    $('#replace-images').overlayImages("http://www.riptideinnovations.com/images/watermark.png"); 
}); 

我加了一步的代碼註釋內一步的解釋,但不要隨意詢問是否要任何進一步的解釋。

我設置了一個小提琴證明:http://jsfiddle.net/pP96f/6/

+0

感謝這就是我一直在尋找的 – JasonDavis 2013-04-08 18:30:48

0

我不知道這是否會幫助,但你可以讓你的所有圖像的div與背景像這樣:

<div style="background-image: url('<your_image>');"></div> 
+0

是的,這是不可能的,因爲我不能改變任何HTML的,這就是爲什麼我要尋找一個完整的JS解決方案 – JasonDavis 2013-04-08 17:19:14

+0

這將需要更多的工作設置div寬度和高度/等。 – lucuma 2013-04-08 17:19:34