我在使用按钮功能时遇到麻烦。我有一个HTML文档,其中为所有页面设置了背景(以保持通用主题)。我在其中一个页面上创建了一个按钮,目的是删除该特定页面上的背景。我使用脚本功能将背景色更改为白色。当我按下按钮时,除了有文本的部分(参见下面的图像)以外,背景都变为白色。我如何才能从本质上删除整个背景的按钮?
这里是我到目前为止的代码:
<body>
<style>
body {
background-image: url(IMG_7305.JPG);
background-size: cover;
background-attachment: fixed;
</style>
<button id="button" type="button" onclick="myFunction()"> Press here to remove the background image </button>
<script>
function myFunction() {
document.getElementById("about").style.backgroundColor = "white"
}
</script>
<p>
I want the background to be cleared... even here!!
</p>
您可以将背景图像放在CSS的body标签上,而不是在CSS的body标签上显示背景图像,而在单击该类时将其删除。
<body class='background'>
<style>
.background {
background-image: url(IMG_7305.JPG);
background-size: cover;
background-attachment: fixed;
</style>
<button id="button" type="button" onclick="myFunction()"> Press here to remove the background image </button>
<script>
function myFunction() {
document.body.classList.remove('background')
}
</script>
<p>
I want the background to be cleared... even here!!
</p>
我也建议添加一个容器和样式,而不是body标签本身。
您需要定位图像的主体,而不仅仅是“ about”元素。
function myFunction() {
document.querySelector("body").style.backgroundImage = "none";
}
body {
background-image: url('https://hips.hearstapps.com/hmg-prod.s3.amazonaws.com/images/beach-quotes-1559667853.jpg');
background-size: cover;
background-attachment: fixed;
}
<button id="button" type="button" onclick="myFunction()"> Press here to remove the background image </button>
<p>
I want the background to be cleared... even here!!
</p>