首页 > 解决方案 > 改变html元素背景图片js

问题描述

我已经搜索了谷歌和在这里,但我无法准确找到我的问题的正确答案我使用了这个代码:

html {
   background: url('../resources/imgs/bgs/mainbg.jpg') no-repeat center center fixed; 
   -webkit-background-size: cover;
   -moz-background-size: cover;
   -o-background-size: cover;
   background-size: cover;
}

我从互联网上获得了一个背景图像,该图像始终位于中心并完全适合浏览器,效果很好,但我遇到了问题。我需要在单击按钮时更改背景图像,但我不知道如何定位 html 标记甚至可能吗?非常感谢 :)

我的问题被标记为重复,但我的问题不仅仅是获取 html 元素的样式,而是将其更改为与仅使用纯 javascript 的代码片段相同

标签: javascripthtmlcssbackground-image

解决方案


您必须同时设置backgroundImagebackgroundSize属性。尝试以下操作:

document.querySelector('#btnSetImage').addEventListener('click', function(){
  var html = document.querySelector('html');
  html.style.backgroundImage = "url('https://www.noodleman.co.uk/images/source/google_merchant_bulk_category_assign/google.jpg')";
  html.style.backgroundSize = 'cover';
});
<button type="button" id="btnSetImage">Set Background Image</button>


推荐阅读