使用 JavaScript 更改图像源

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7312553/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 01:44:58  来源:igfitidea点击:

Change image source with JavaScript

javascriptimageonclicksrc

提问by Alvaro Arregui

So I'm new with JavaScript (this is actually my first attempt to make something work) and I'm having a bit of trouble. I thought I had enough knowledge to make this work, I've even googled for tutorials and scripts that could help me work this out but nothing really helped.

所以我是 JavaScript 新手(这实际上是我第一次尝试做一些事情)并且我遇到了一些麻烦。我以为我有足够的知识来完成这项工作,我什至在谷歌上搜索了可以帮助我解决这个问题的教程和脚本,但没有任何帮助。

I can't seem to change the image source, heres the code that I have so far:

我似乎无法更改图像源,这是我目前拥有的代码:

<script type="text/javascript">
    function changeImage(a) {
        document.getElementById("img").src=a.src;
    }
</script>
<div id="main_img">
    <img id="img" src="1772031_29_b.jpg">
</div>
<div id="thumb_img">
    <img src='1772031_29_t.jpg'  onclick='changeImage("1772031_29_b.jpg");'>
    <img src='1772031_55_t.jpg'  onclick='changeImage("1772031_55_b.jpg");'>
    <img src='1772031_53_t.jpg'  onclick='changeImage("1772031_53_b.jpg");'>
</div>

Could anyone please explain if I'm doing something wrong? Or maybe I'm missing something? Help me please :-)

如果我做错了什么,有人可以解释一下吗?或者也许我错过了什么?请帮帮我 :-)

回答by

function changeImage(a)so there is no such thing as a.src=> just use a.

function changeImage(a)所以没有a.src=> 之类的东西,只需使用a.

demo here

演示在这里

回答by Shadow Wizard is Ear For You

If you will always have the pattern on _binstead of _tyou can make it more generic by passing reference to the image itself:

如果您将始终使用该模式_b而不是_t您可以通过传递对图像本身的引用来使其更通用:

onclick='changeImage(this);'

Then in the function:

然后在函数中:

function changeImage(img) {
    document.getElementById("img").src = img.src.replace("_t", "_b");
}

回答by Tracker1

Your only real problem is you are passing a string, not an object with a .srcproperty

您唯一真正的问题是您传递的是字符串,而不是具有.src属性的对象

Some suggestions:

一些建议:

  • Use a naturally clickable element trigger, such as <button>
  • Use data-prefixed attributes for event data on the element
  • Use late bound events when the DOM is ready.
  • 使用自然可点击的元素触发器,例如 <button>
  • data-为元素上的事件数据使用前缀属性
  • 当 DOM 准备好时使用后期绑定事件。

Markup:

标记:

<div id="main_img">
  <img id="img" src="1772031_29_b.jpg">
</div>
<ul id="thumb_img">
  <li><button data-src='1772031_29_b.jpg'><img src='1772031_29_t.jpg' /></button></li>
  <li><button data-src='1772031_55_b.jpg'><img src='1772031_55_t.jpg' /></button></li>
  <li><button data-src='1772031_53_b.jpg'><img src='1772031_53_t.jpg' /></button></li>
</ul>

JavaScript:

JavaScript:

If you need to support IE and other legacy browsers, Use a proper polyfill for Array.from

如果您需要支持 IE 和其他旧版浏览器,请为 Array.from使用适当的 polyfill

function clickedButton(btn, event) {
  document.getElementById('img').src = btn.getAttribute('data-src');
}

function bindClick(btn) {
  btn.addEventListener('click', clickedButton.bind(null,btn));
}

// Setup click handler(s) when content is loaded
document.addEventListener("DOMContentLoaded", function(){
  Array.from(document.querySelectorAll('#thumb_img > button'))
    .forEach(bindClick));
});


Edit: Vanilla JS for modern browsers.

编辑:适用于现代浏览器的 Vanilla JS。

回答by Ronald

I also tube that problem. But solve it by an instance of an image every time you change the source (image).

我也管那个问题。但是每次更改源(图像)时,都可以通过图像的实例来解决它。

It seems that would be called onload only once. But this way, you can change image whenever you want.

似乎只会调用一次 onload 。但是这样,您可以随时更改图像。

function chageIcon(domImg,srcImage)
    {
        var img = new Image();
        img.onload = function()
        {
            // Load completed
            domImg.src = this.src;
        };
        img.src = srcImage;
    }

Mode use.

模式使用。

chageIcon(document.getElementById("img"),"newIcon.png");

回答by ShaneC

You've got a few changes (this assumes you indeed still want to change the image with an ID of IMG, if not use Shadow Wizard's solution).

您有一些更改(这假设您确实仍然希望使用 IMG 的 ID 更改图像,如果不使用 Shadow Wizard 的解决方案)。

Remove a.srcand replace with a:

删除a.src并替换为a

<script type="text/javascript">
function changeImage(a) {
    document.getElementById("img").src=a;
}
</script>

Change your onclickattributes to include a string of the new image source instead of a literal:

更改您的onclick属性以包含新图像源的字符串而不是文字:

onclick='changeImage( "1772031_29_b.jpg" );'

回答by qwerty helper

The problem was that you were using .srcwithout needing it and you also needed to differentiate which imgyou wanted to change.

问题是您在.src不需要它的情况下使用它,您还需要区分img您想要更改的内容。

function changeImage(a, imgid) {
    document.getElementById(imgid).src=a;
}
<div id="main_img">
    <img id="img" src="1772031_29_b.jpg">
</div>
<div id="thumb_img">
    <img id="1" src='1772031_29_t.jpg'  onclick='changeImage("1772031_29_b.jpg", "1");'>
    <img id="2" src='1772031_55_t.jpg'  onclick='changeImage("1772031_55_b.jpg", "2");'>
    <img id="3" src='1772031_53_t.jpg'  onclick='changeImage("1772031_53_b.jpg", "3");'>
</div>

回答by user7338225

The Following Example Program used to change the image src attribute for every 100 milliseconds. you may call the given function as your wish.

以下示例程序用于每 100 毫秒更改一次图像 src 属性。您可以根据需要调用给定的函数。

<html>
<head>
</head>
<body>
<img src="bulboff.jpg" height=200 width=200 id="imm" align="right">

<script type="text/javascript">

function bulb() {

var b = document.getElementById("imm");

if(b.src.match("bulboff.jpg")) {
 b.src = "bulbon.jpg";
}
 else {

 b.src="bulboff.jpg";
}
}
 setInterval(bulb,100);
</script>
</body>
</html>

回答by Palak Jain

Instead of writing this,

而不是写这个,

<script type="text/javascript">
function changeImage(a) {
    document.getElementById("img").src=a.src;
}
</script>

try:

尝试:

<script type="text/javascript">
function changeImage(a) {
document.getElementById("img").src=a;
}
</script>

回答by Rajashekhar

 <script type="text/javascript">
        function changeImage(a) {
    var picName=a.substring(1,a.length-1);
            document.getElementById("image").src=picName;
        }
 </script>

 <div id="main_img">
     <img id="image" src="app.jpg">
 </div>

 <div id="thumb_img">
     <img src='app.jpg'  onclick="changeImage('+5steps.jpg+');">
     <img src='5steps.jpg'  onclick="changeImage('+award.png+');">
     <img src='award.png'  onclick="changeImage('+app.jpg+');">
 </div>

Use the above code by placing this html file and pics(take care in namings, beacause I have given the above code with my pic names) in same folder you will get...

使用上面的代码,将这个 html 文件和图片(注意命名,因为我已经给了上面的代码和我的图片名称)在同一个文件夹中,你会得到...

回答by Michele S.

Hi i tried to integrate with your code.

嗨,我试图与您的代码集成。

Can you have a look at this?

你能看看这个吗?

Thanks M.S

谢谢女士

<!DOCTYPE html>
<html>
<head>

<!--TODO: need to integrate this code into the project to change images added 05/21/2016:-->

<script type="text/javascript">
    function changeImage(a) {
        document.getElementById("img").src=a;
    }
</script>


 
<title> Fluid Selection </title>
<!-- css -->
 <link rel="stylesheet" href="bootstrap-3/css/bootstrap.min.css">
 <link rel="stylesheet" href="css/main.css">
<!-- end css -->
<!-- Java script files -->
<!-- Date.js date os javascript helper -->
    <script src="js/date.js"> </script>

<!-- jQuery (necessary for Bootstrap's JavaScript plugins) -->
 <script src="js/jquery-2.1.1.min.js"></script>

<!-- Include all compiled plugins (below), or include individual files as needed -->
 <script src="bootstrap-3/js/bootstrap.min.js"> </script>
 <script src="js/library.js"> </script>
 <script src="js/sfds.js"> </script>
 <script src="js/main.js"> </script>

<!-- End Java script files -->

<!--added on 05/28/2016-->

<style>
/* The Modal (background) */
.modal {
    display: none; /* Hidden by default */
    position: fixed; /* Stay in place */
    z-index:40001; /* High z-index to ensure it appears above all content */ 
    padding-top: 100px; /* Location of the box */
    left: 0;
    top: 0;
    width: 100%; /* Full width */
    height: 100%; /* Full height */
    overflow: auto; /* Enable scroll if needed */
   
    background-color: rgba(0,0,0,0.9); /* Black w/ opacity */
}

/* Modal Content */
.modal-content {
    position: relative;
    background-color: #fefefe;
    margin: auto;
    padding: 0;
    border: 1px solid #888;
    width: 40%;
    box-shadow: 0 4px 8px 0 rgba(0,0,0,0.2),0 6px 20px 0 rgba(0,0,0,0.19);
    -webkit-animation-name: animatetop;
    -webkit-animation-duration: 0.4s;
    animation-name: animatetop;
    animation-duration: 0.4s
 opacity:.5; /* Sets opacity so it's partly transparent */ -ms-filter:"progid:DXImageTransform.Microsoft.Alpha(Opacity=50)"; 
 /* IE     
 transparency */ filter:alpha(opacity=50); /* More IE transparency */ z-index:40001; } 
}

/* Add Animation */
@-webkit-keyframes animatetop {
    from {top:-300px; opacity:0} 
    to {top:0; opacity:1}
}

@keyframes animatetop {
    from {top:-300px; opacity:0}
    to {top:0; opacity:1}
}

/* The Close Button */
.close {
    
}

.close:hover,
.close:focus {
    color: #000;
    text-decoration: none;
    cursor:pointer;
}

/* The Close Button */
.close2 {
    
}


.close2:focus {
    color: #000;
    text-decoration: none;
    cursor:pointer;
}

.modal-header {
 color: #000;
    padding: 2px 16px;
 }

.modal-body {padding: 2px 16px;}
 
 
}

.modal-footer {
    padding: 2px 16px;
    background-color: #000099;
    color: white;
}


</style>

<script>
 $(document).ready(function() {
 
 
  $("#water").click(function(event){
   var $this= $(this);
   if($this.hasClass('clicked')){
    $this.removeClass('clicked');
    SFDS.setFluidType(0);
    $this.find('h3').text('Select the H20 Fluid Type');
    }else{
     SFDS.setFluidType(1);
     $this.addClass('clicked');
     $this.find('h3').text('H20 Selected');

   }
  });
  
  $("#saline").click(function(event){
   var $this= $(this);
   if($this.hasClass('clicked')){
    $this.removeClass('clicked');
    SFDS.setFluidType(0);
    $this.find('h3').text('Select the NaCL Fluid Type');
    }else{
     SFDS.setFluidType(1);
     $this.addClass('clicked');
     $this.find('h3').text('NaCL Selected');
     
  
  
   }
  });
  
 });
</script>
</head>
<body>
<div class="container-fluid">
 <header>
  <div class="row">
   <div class="col-xs-6">
    <div id="date"><span class="date_time"></span></div>
   </div>
   <div class="col-xs-6">
    <div id="time" class="text-right"><span class="date_time"></span></div>
   </div>
  </div>
 </header>

 <div class="row">
  <div class="col-md-offset-1 col-sm-3 col-xs-8 col-xs-offset-2 col-sm-offset-0">
   <div id="fluid" class="main_button center-block">
    <div class="large_circle_button, main_img"> 
     <h2>Select<br>Fluid</h2>
     <img class="center-block large_button_image" src="images/dropwater.png" alt=""/> 
    </div>
    <h1></h1>
   </div>
  </div>
  <div class=" col-md-6 col-sm-offset-1 col-sm-8 col-xs-12">
   <div class="row">
    <div class="col-xs-12">
     <div id="water" class="large_rectangle_button">
      <div class="label_wrapper">
       <h3>Sterile<br>Water</h3>
      </div>
      <div id="thumb_img" class="image_wrapper">
       <img src="images/dropsterilewater.png" alt="Sterile Water" class="sterile_water_image" onclick='changeImage("images/dropsterilewater.png");'>
      </div>
      <img src="images/checkmark.png" class="button_checkmark" width="96" height="88">
     </div>
    </div>
    <div class="col-xs-12">
     <div id="saline" class="large_rectangle_button">
      <div class="label_wrapper">
       <h3>Sterile<br>0.9% NaCL</h3>
      </div>
      <div class="image_wrapper">
       <img src="images/cansterilesaline.png" alt= "Sterile Saline" class="sterile_salt_image" onclick='changeImage("images/imagecansterilesaline.png");'>
      </div>
      <img src="images/checkmark.png" class="button_checkmark" width="96" height="88">

     </div>
    </div>
    <div class="col-xs-12">
     <div class="small_rectangle_button">
      
      <!-- Trigger/Open The Modal -->
      <div id="myBtn" class="label_wrapper">
       <h3>Change<br>Cartridge</h3>
      </div>
      <div class="image_wrapper">
       <img src="images/changecartridge.png" alt="" class="change_cartrige_image" />
      </div>
     </div>
    </div>
    
     <!-- The Modal -->
     <div id="myModal" class="modal">

       <!-- Modal content -->
       <div class="modal-content">
      <div class="modal-header">
        <span class="close"><img src="images/x-icon.png"></span>
        <h2>Change Cartridge Instructions</h2>
      </div>
      <div class="modal-body">
        <h4>Lorem ipsum dolor sit amet, dicant nonumes volutpat cu eum, in nulla molestie vim, nec probo option iracundia ut. Tale inermis scripserit ne cum, his no errem minimum commune, usu accumsan omnesque in. Eu has nihil dolor debitis, ad nobis impedit per. Dicat mnesarchum quo at, debet abhorreant consectetuer sea te, postea adversarium et eos. At alii dicit his, liber tantas suscipit sea in, id pri erat probatus. Vel nostro periculis dissentiet te, ut ubique noster vix. Id honestatis disputationi vel, ne vix assum constituam.</h4>                                                   
                           <a href="#"><img src="images/video-icon.png" alt="click here for video"> </a>
                           <a href="#close2" title="Close" class="close2"><img src="images/cancel-icon.png" alt="Cancel"></a>

                          
      </div>
      <div class="modal-footer">
        <h4></h4>
      </div>
       </div>

     </div>
     
     <!--for comparison-->


     

     
     <script>
     // Get the modal
     var modal = document.getElementById('myModal');

     // Get the button that opens the modal
     var btn = document.getElementById("myBtn");

     // Get the <span> element that closes the modal
     var span = document.getElementsByClassName("close")[0];
     

     // When the user clicks the button, open the modal 
     btn.onclick = function() {
      modal.style.display = "block";
     }

     // When the user clicks on <span> (x), close the modal
     span.onclick = function() {
      modal.style.display = "none";
     }

     // When the user clicks anywhere outside of the modal, close it
     window.onclick = function(event) {
      if (event.target == modal) {
       modal.style.display = "none";
      }
      
      
     }
     </script>
                    

    
    
    
    
    
   </div>
  </div>
 </div>
</div>
<footer class="footer navbar-fixed-bottom">
 <div class="container-fluid">
  <div class="row cols-bottom">
   <div class="col-sm-3">
    <a href="main.html">
    <div class="small_circle_button">     
     <img src="images/buttonback.png" alt="back to home" class="settings"/> <!--  width="49" height="48" -->
    </div>
   </div></a><div class=" col-sm-6">
    <div id="stop_button" >
     <img src="images/stop.png" alt="stop" class="center-block stop_button" /> <!-- width="140" height="128" -->
    </div>
     
   </div><div class="col-sm-3">
    <div id="parker" class="pull-right">
     <img src="images/parkerlogo.png" alt="parkerlogo" /> <!-- width="131" height="65" -->
    </div>
   </div>
  </div>
 </div>
</footer>


</body>
</html>