使用JavaScript在其他图像上添加透明图像

时间:2013-04-08 17:11:37

标签: javascript css

我需要在页面上的所有图像上添加透明图像。目标是如果用户进行简单的右键单击并保存图像,他们将保存透明图像。

我确实意识到这不是一种保证方法,并且不存在以防止图像被盗,而只是客户想要添加的措施,以防止普通的非技术人员保存图像。

  • 使用JavaScript我想查找某个Div中的所有图像或所有图像。
  • 在这些图像上方应用新的图像叠加层,这些图像的宽度和高度与其覆盖的图像相同

我不确定如何使用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 个答案:

答案 0 :(得分: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/

答案 1 :(得分:0)

我不知道这是否会有所帮助,但你可以使用这样的背景制作你的图像所有div:

<div style="background-image: url('<your_image>');"></div>
相关问题