在JavaScript中实现可关闭的悬浮广告通常涉及到创建一个广告元素,并为其添加一个关闭按钮。以下是一个简单的示例代码,展示了如何实现这样的功能:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>悬浮广告示例</title>
<style>
#ad-container {
position: fixed;
top: 10px;
right: 10px;
width: 150px;
height: 150px;
background-color: #f1f1f1;
border: 1px solid #ccc;
box-shadow: 0 0 10px rgba(0,0,0,0.1);
z-index: 1000;
}
#close-ad {
position: absolute;
top: 5px;
right: 5px;
cursor: pointer;
}
</style>
</head>
<body>
<div id="ad-container">
<span id="close-ad">X</span>
<p>这是一个悬浮广告。</p>
</div>
<script>
document.getElementById('close-ad').addEventListener('click', function() {
document.getElementById('ad-container').style.display = 'none';
});
</script>
</body>
</html>
如果关闭按钮不起作用,可以尝试以下步骤:
close-ad
元素的ID正确无误。window.onload
事件:window.onload
事件:通过以上方法,可以有效实现一个简单且用户友好的可关闭悬浮广告。
领取专属 10元无门槛券
手把手带您无忧上云