这可能是一个基本问题,但是如何在 Javascript 中制作一条水平线(也称为水平线),类似于 html <hr>
标签?我希望能够设置它的颜色和厚度,就像 <hr>
一样。标签允许我。
我有一个网站,我需要在 <script
中执行此操作> 标签(连同一些附带的代码)。我不能使用 <hr>
因为我的一些用户没有启用 JS;所以对他们来说没有<script>
标签内容会显示,但是 <hr>
仍会显示(我不希望这种情况发生)。
最佳答案
首先解决问题:
I can't use
<hr>
since some of my users don't have JS enabled; so for them none of the<script>
tag contents will show, but<hr>
will still show (and I don't want that to happen).
您可以将类(class)添加到您的 <html>
JavaScript 中的元素(如果您不需要 IE 9 支持,请使用 classList
):
document.documentElement.className += ' has-js';
然后为您的 <hr>
设置样式除非支持 JavaScript,否则不会出现:
<hr class="hey-that’s-my-line" />
.hey-that’s-my-line {
display: none;
/* change its height & colour here */
}
html.has-js .hey-that’s-my-line {
display: block;
}
现在,回答您的问题:您可以使用 DOM API 创建元素并将它们插入到您的文档中。在这个答案中完全涵盖有点多,但 MDN 有 a good introduction .
var hr = document.createElement('hr');
document.body.appendChild(hr); // inserts it at the end of <body>;
// appendChild() inserts at the end of any node,
// generally
var ref = document.getElementById('reference-point');
ref.parentNode.insertBefore(hr, ref); // inserts it before the element
// with the id 'reference-point'
关于javascript - 使用JS绘制横线,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39682844/