为图像添加onclick或按钮

时间:2013-09-24 15:07:43

标签: javascript html5

我有以下代码:

<a onClick="change('img1');" href="#"><img src="../name_footer/alexis-name.png" /></a>

当点击alexis-name图像时,它会调用另一个图像'img1' 当调用img1时,我想在img1屏幕上显示一个按钮,但我不知道该怎么做。

这是js for change()

function change(v) {
        var confirm = document.getElementById("target");
                 if (v == "imgA") {target.className = "cast1";}
            else if (v == "imgB") {target.className = "cast2";}
            else if (v == "imgC") {target.className = "cast3";}
            else if (v == "imgD") {target.className = "cast4";}

            else if (v == "imgE") {target.className = "question";}

            else if (v == "img1") {target.className = "bio1";}
            else if (v == "img2") {target.className = "bio2";}
            else if (v == "img3") {target.className = "bio3";}
            else if (v == "img4") {target.className = "bio4";}
                 else {target.className = "chart";}
}
document.querySelector("button").addEventListener("click", function(){
    document.querySelector("div").style.display = "block";
});

我应该使用多个onclicks吗?

我尝试过以下方法: 添加一个div,其中包含当用户点击img1时显示的绝对位置。

<a onClick="change('img1');" href="#"><img src="../name_footer/alexis-name.png" /></a>
<div id=blah style="position:absolute; top:500px; left:700px; width:130px; height:130px;"><a href="domain"></a>

1 个答案:

答案 0 :(得分:1)

jsFiddle Demo

查看更多代码会有所帮助,例如函数change的实现。你的问题有点模糊。基本上要有一些显示和点击,你可以使用javascript和onclick处理程序。这不应该是内联的。我添加了一个id,以便您可以看到如何选择元素。这是一个非常基本的演示,你有很大的空间可以扩展它以使它适合你的情况。

<html><head>
<script>
 //wait for DOM ready to select image element
 window.onload = function(){
  //select anchor element
  var link = document.getElementById("link");
  //attach click handler
  link.onclick = function(){
   //code to execute when element is clicked
   change('img1');
  };
 };

 //function for handler
 function change(arg){
  //select image element
  var image = document.getElementById("image");
  //change source
  image.src = "../name_footer/" + arg + ".png";//this will change it to /img1.png
  //create a button
  var button = document.createElement("input");
  button.id = "img1Button";
  button.type = "button";
  button.value = "Display";
  //append button after img1
  image.parentNode.appendChild(button);
  //attach handler to button
  button.onclick = function(){
   //code for button
   alert("Button");
  };
 }
 //select anchor element
 var link = document.getElementById("link");
 //attach click handler
 link.onclick = function(){
  //code to execute when element is clicked
  change('img1');
 };
</script></head>
<body>
 <a id="link" href="#"><img id="image" src="../name_footer/alexis-name.png" /></a>
</body>
</html>