页面加载后交换(替换)图像src?

时间:2015-07-12 16:16:38

标签: javascript jquery image

我有一个由外部脚本放置的图像:

<img src="https://example1.com/image1.png" id="image1">

我需要用我的图像交换(替换)图像src,

<img src="https://example2.com/image2.png" id="image2">

原始脚本加载后。

我找到了通过点击或鼠标悬停更改图像src的解决方案,或者更复杂的图像集,但是我可以强制在页面加载图像交换单个图像而无需执行其他操作吗? 提前感谢您的建议。

4 个答案:

答案 0 :(得分:1)

如果我说得对,你想在页面加载时执行更改:

$(function() {
     $("#image1").attr("src", "https://example2.com/image2.png")
})

答案 1 :(得分:1)

您需要在window.load事件中执行此操作。

  1. 如果您想在DOM加载后交换
  2. $(document).ready(function () {
      $('#image1').attr('src', 'http://placehold.it/150x350');
    });
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <img src="http://placehold.it/350x150" id="image1">

    1. 如果您想在加载原始图片后交换
    2.   

      有时你想操纵图片和$(文件).ready()   如果访客没有图像,你将无法做到这一点   已加载。在这种情况下,您需要初始化jQuery   图像完成加载时的对齐功能。

      但它没用。用户几乎无法看到原始图像(它将很快交换)。

      $(window).load(function () {
        $('#image1').attr('src', 'http://placehold.it/150x350');
      });
      <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
      <img src="http://placehold.it/350x150" id="image1">

      http://www.sitepoint.com/types-document-ready/

答案 2 :(得分:0)

你走了,

 $(function(){
      $('#image1').attr('src', $('#image2').attr('src'));
   })

<强>解释

$('#image2').attr('src')将返回src中图片的img id=image2属性,并且src将在img id=image1

的src属性中设置

这将自动触发,因为jquery确保,

$(function(){
   //wherever you write here will be executed only after DOM load, no external trigger needed
})

希望有所帮助:)

答案 3 :(得分:0)

如果您想尽快更改图像,可以使用DOMNodeInserted事件。

    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <body>
        <script>
            // Swap out the image as soon as the DOM is inserted
            $('body').on('DOMNodeInserted', '#image1', function(e) {
                $("#image1").attr("src", "http://placehold.it/100x100").attr("id", "image2");
            });
        </script>
        
        <div id="js-putImageHere"></div>
        
        <script>
            // Here is the external code that loads the image you don't want
            $("#js-putImageHere").html('<img src="http://placehold.it/350x150" id="image1">');
        </script>
    </body>