javascript - 改变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 的代码片段相同
解决方案
您必须同时设置backgroundImage
和backgroundSize
属性。尝试以下操作:
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>
推荐阅读
- reactjs - 如何使用 React Table 库创建一列仅包含图标的单元格?
- laravel - 按降序打印结果
- csv - 将 CSV 加载到 Apache Beam 上,其中某些字段中有逗号
- node.js - 如何在 Mocha 挂钩之前在异步中设置测试数据?
- elasticsearch - 获取 ElasticSearch simple_query_string 以支持模糊
- java - 按下按钮状态的 ConstraintLayout
- c# - 引用字典时遇到问题
- flask - 使用 Flask-Caching 的 delete_memoized 删除函数中所有与变量相关的变量
- android - mvp 回收器适配器不显示数据
- docker - 默认启用 scl 工具集