In web design, pictures are one of the most common elements. When users browse web pages, they sometimes encounter situations where they need to close images. At this time, we can use JavaScript to implement the function of closing images. This article will introduce how to use JavaScript to implement the image closing function.
1. Requirements Analysis
After inserting a picture into the page, there needs to be a way to close the picture so that the user can continue browsing the page. By analyzing the requirements, we can determine that the following requirements are required to implement this function:
2. Implementation ideas
Based on the above demand analysis, we can design the following implementation ideas:
3. Implementation steps
<div id="imgBox"> <img src="yourImage.jpg"> </div>
#imgBox{ display: none; position: fixed; top: 0; left: 0; height: 100%; width: 100%; background-color: rgba(0,0,0,0.7); z-index: 9999; } #imgBox img{ position: absolute; top: 50%; left: 50%; transform: translate(-50%,-50%); max-width: 90%; max-height: 90%; }
var imgBox = document.getElementById('imgBox'); imgBox.addEventListener('click',function(e){ if(e.target === imgBox || e.target.nodeName === 'SPAN'){ imgBox.style.display = 'none'; } });
In the above code, we added a click event to the div element. When the user clicks the div element, the code will determine whether the target element of the click event is the div element itself or a certain A close button (in this example, we used a span element as the close button), if so, the div element is hidden.
4. Complete code
The core code is as follows:
<div id="imgBox"> <img src="yourImage.jpg"> <span>关闭</span> </div>
#imgBox{ display: none; position: fixed; top: 0; left: 0; height: 100%; width: 100%; background-color: rgba(0,0,0,0.7); z-index: 9999; } #imgBox img{ position: absolute; top: 50%; left: 50%; transform: translate(-50%,-50%); max-width: 90%; max-height: 90%; } #imgBox span{ position: absolute; top: 10px; right: 10px; color: #fff; cursor: pointer; } #imgBox span:hover{ text-decoration: underline; }
var imgBox = document.getElementById('imgBox'); imgBox.addEventListener('click',function(e){ if(e.target === imgBox || e.target.nodeName === 'SPAN'){ imgBox.style.display = 'none'; } });
5. Summary
Through the above steps, we successfully used JavaScript to close the image Function. When the user clicks an area outside the image or a close button, the image will disappear from the page. The function's code structure is clear, easy to understand and maintain, and it executes very quickly. Using this function can improve the user's operating experience and allow users to browse the web more conveniently.
The above is the detailed content of JavaScript implements picture closing. For more information, please follow other related articles on the PHP Chinese website!