如何使用HTML在点击时显示图像
偶尔,网页可能包含与该网页内容不相关的图像。这些不寻常的图像在网页加载时被加载,这就增加了加载时间。网页上更多的加载时间会减少访问者的数量。
在这篇文章中,我们想出了一个解决这个问题的办法。我们将学习如何使用HTML、CSS和JavaScript在用户点击图片时才显示图片。
使用JavaScript更改属性的显示属性:在这个方法中,我们将使用style属性在
标签内设置display属性。我们必须为图像设置“display: none”。之后,当用户单击按钮时,我们将调用一个JavaScript函数,该函数将访问图像,将其display属性更改为block。
步骤:
在HTML代码中创建元素。
为元素添加样式,并将display属性设置为无。
创建一个JavaScript “show()”函数,可以访问图片并将display属性改为block。
在HTML代码中添加按钮,当用户点击它时调用 “show() “函数。
示例:
/* Set display to none for image*/
#image {
display: none;
}
GeeksforGeeks
Click on the button to see image
"https://media.geeksforgeeks.org/wp-content/uploads/20210915115837/gfg3.png"
alt="GFG image" />
function show() {
/* Access image by id and change
the display property to block*/
document.getElementById('image')
.style.display = "block";
document.getElementById('btnID')
.style.display = "none";
}
输出:
使用 标签的空src性:显然,如果有一个空的src值,用户将无法看到网页上的图片。我们将使用JavaScript函数来设置src属性的值,这是在用户点击按钮时实现的。然而,一些浏览器,如Chrome,在使用这种方法时,并没有删除破碎的图像图标。
步骤:
创建元素,其src属性为空。
在JavaScript中创建 “show() “函数,它可以获得图像并将图像源链接添加到src属性中。
添加HTML按钮,当用户点击它时,调用 “show() “函数。
示例:
GeeksforGeeks
Click on the button to see image
function show() {
/* Get image and change value
of src attribute */
let image = document.getElementById("image");
image.src =
"https://media.geeksforgeeks.org/wp-content/uploads/20210915115837/gfg3.png"
document.getElementById("btnID")
.style.display = "none";
}
输出:
使用Bootstrap模态:我们将使用一个Bootstrap模态,在点击按钮的同时显示一张图片。我们需要将bootstrap CDN与HTML代码结合起来使用。我们可以将bootstrap CDN添加到我们的HTML文件中,就像下面的示例代码中添加的那样。
步骤:
在HTML文件中添加bootstrap CDN。
创建Bootstrap模态,并在模态的主体中添加一个图片。
创建一个HTML按钮来触发一个模态。
示例:
"https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css"
integrity=
"sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm"
crossorigin="anonymous">
GeeksforGeeks
Click on the button to see image
id="exampleModal"
tabindex="-1"
role="dialog"
aria-labelledby="exampleModalLabel"
aria-hidden="true">
输出: