如何使用Javascript切换HTML元素 [英] How to toggle HTML element using Javascript

查看:82
本文介绍了如何使用Javascript切换HTML元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

大家好,我正在开发一个网站,目前我仍然坚持这个代码

Hello guys, i am currently developing a website and currently im stuck at this code

<div>
                                <img id="tile" src="tilehead1.png"/><br>
                                <img id="hidden2" style="visibility: hidden" src="hide1.png"/><br>
                                <img  önclick="swapImage()" id="readMore" src="ReadMore.jpg"/><img src=".neighbour.png"/><br>
                                <img id="img" src="image1.png"/>
                                </br></br></br>
                                
                            </div>





上面的html代码用于替换使用图像阅读更多功能,id为隐藏的图像2最初是隐藏的,但是当用户点击id为readMore的图像时,它将其src属性值切换到另一个图像以获得完成功能。问题是,当隐藏id为隐藏2的图像时,由于之前的
元素,其他图像之间留下了巨大的差距,我希望能够在图像中添加br元素。用户点击readMore



这里是我的javaScript代码





the above html code is for displating the read more functionality using images, the image for id of"hidden2" is initially hidden but when the user clicks on the image for id "readMore" it switches its "src" attribute value to another image for "done" functionality. the problem is, when the image for id of "hidden 2" is hidden it leaves a huge gap between other images because of the
element before it, i want to be able to add the br element along with the image when a user clicks "readMore"

here is my javaScript code

<script language="Javascript" type="text/javascript">
intImage = 2;
function swapImage() {
switch (intImage) {
 case 1:
   readMore.src = "ReadMore.jpg"
   document.getElementById('hidden2').style.visibility= "hidden";
   intImage = 2
   return(true);
   
   

   
   
case 2:
   readMore.src = "done.png"
   document.getElementById('hidden2').style.visibility= "visible";
   intImage = 1
   return(false);
 }
}
</script>





帮助我添加切换功能
元素及其包含的图像(hidden2),我试过但我失败了



谢谢



help me to add the functionality of toggling the
element along with the image that it contains (hidden2), i tried but i failed

Thank you

推荐答案

The code is working fine as far as toggling the image('hidden2') is concerned. However, visibility:hidden css property leaves the space behind. 

So you can go with the display property by which the image space will be removed.




//for hiding
document.getElementById('hidden2').style.display= "none";
//for showing
document.getElementById('hidden2').style.display= "block";

//Also, It is good to refer the 'readMore' image by the document.getElementById() function.


这篇关于如何使用Javascript切换HTML元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆