<!DOCTYPE html>
<html lang="zh">
<head>
<meta charset="UTF-8">
<title>Title</title>
<style>
.box{
width: 100px;
height: 100px;
background-color: red;
transition: all 1s linear;
}
.box2{
width: 200px;
height: 200px;
background-color: deepskyblue;
}
</style>
</head>
<body>
<div class="box"></div>
</body>
</html>
<script src="../网站后台/js/jquery-3.4.1.js"></script>
<script>
const box = document.querySelector('.box');
// 通过添加类名更改样式
box.onclick = function () {
box.className += 'box2';
};
const img = document.createElement('img');
img.style = "position: absolute; top: -9999px; max-width: 100px; max-height: 100px;"
box.onclick = function () {
box.style.width = '200px';
box.style.height = '200px';
box.style.backgroundColor= 'green'; // CSS中通过-连接的样式名,在JS中变成驼峰命名 background-color => backgroundColor
};
box.onclick = function () {
box.style['width'] = '200px';
box.style['height'] = '200px';
box.style['background-color']= 'orange'; // 这样写与CSS中的命名一致,不用驼峰命名
};
// 可以一次设置多条样式
box.onclick = function () {
box.style.cssText = `
width: 200px;
height: 200px;
background-color: yellow`
};
box.onclick = function () {
/**
* @desc 语法:object.setProperty(propertyname, value, priority)
* @param {string} propertyname - 必需。一个字符串,表示创建或修改的属性
* @param {string} [value] - 可选。新的属性值
* @param {string} [priority] - 可选。字符串,规定是否需要设置属性的优先级 important。
* */
box.style.setProperty("width", "200px");
box.style.setProperty("height", "200px");
box.style.setProperty("background-color", "pink", "important");
};
/*========= 上面↑是javascript的方法,下面↓是jquery中的方法 ===========*/
const $box = $('.box');
$box.click(function () {
$box.css('width', '200px');
$box.css('height', '200px');
$box.css('background-color', 'purple');
$box.css('width', '200px').css('height', '200px').css('background-color', 'grey');
$box.css({
width: '200px',
height: '200px',
backgroundColor: 'blue' // 驼峰命名
});
$box.attr('style', `width: 200px; height: 200px; background-color: yellow`)
})
</script>
【合集】JavaScript 和 Jquery 设置元素的样式
于 2021-01-02 15:39:48 首次发布