javascript - 如何将CSS添加到Javascript中?

标签 javascript jquery html css

假设这是我的 javascript 代码:

var bottomChild = document.createElement('div');
bottomChild.id = 'bottomChildId';
bottomChild.style.width = '100px';
bottomChild.style.position = 'relative';
bottomChild.style.overflowY = 'scroll';
bottomChild.style.background = 'red';
bottomChild.style.top = '0px';
bottomChild.style.borderLeft = '0px solid #E4E7EA';
bottomChild.style.height = '200px';
document.body.appendChild(bottomChild);

现在我想将以下 css 添加到 bottomChild 中:

::-webkit-scrollbar {
    width: 22px;
}
::-webkit-scrollbar-track {
    -webkit-box-shadow: inset 0 0 6px rgba(0,0,0,0.3); 
    -webkit-border-radius: 10px;
    border-radius: 10px;
}

请帮助将这些 css 添加到动态 javascript div 中。

最佳答案

您可以像这样添加类 - div(id).className = 'target';

在你的情况下添加:

bottomChild.className = 'target';

Js:

var bottomChild = document.createElement('div');
bottomChild.id = 'bottomChildId';
bottomChild.style.width = '100px';
bottomChild.style.position = 'relative';
bottomChild.style.overflowY = 'scroll';
bottomChild.style.background = 'red';
bottomChild.style.top = '0px';
bottomChild.style.borderLeft = '0px solid #E4E7EA';
bottomChild.style.height = '200px';
bottomChild.className = 'target';
document.body.appendChild(bottomChild);

CSS:

.target {
    background:#000000 !important;
    // etc.
}
.target::-webkit-scrollbar {
    width: 22px;
}
.target::-webkit-scrollbar-track {
    -webkit-box-shadow: inset 0 0 6px rgba(0,0,0,0.3); 
    -webkit-border-radius: 10px;
    border-radius: 10px;
}

工作 fiddle :https://jsfiddle.net/mL8g3qLf/

关于javascript - 如何将CSS添加到Javascript中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41195495/

相关文章:

Jquery分割函数

javascript - 仅更改背景图像平滑,前面没有文字

java - Jsoup - 如何抓取当前播放歌曲的广播网站?

jquery - pjax 无法与 laravel 一起使用

javaScript 提升无法正常工作

javascript - 更改 javascript 版本后 onclick() 失败

javascript - jquery 工具提示显示 div 的内容

Javascript/Jquery 代码在第一个事件上运行一次,在第二个事件上运行两次,依此类推

javascript - 表格网格内的随机可见 div

javascript - React - 按下按钮时 native ' Redux Uncaught Error: Actions must be plain objects. Use custom middleware for async actions'