这可能是一个基本的问题,但要怎样才能在Javascript中的水平线(a.k.a水平线),类似的HTML标签<hr>
?我希望能够设置它的颜色和厚度,就像<hr>
标签允许我一样。使用JS画一条水平线
我有一个网站,我需要做这样的<script
>标签内(连同一些相关的代码)。我不能使用<hr>
,因为我的一些用户没有启用JS;所以对于他们来说,<script>
标签内容都不会显示,但<hr>
仍然会显示(我不希望发生这种情况)。
这可能是一个基本的问题,但要怎样才能在Javascript中的水平线(a.k.a水平线),类似的HTML标签<hr>
?我希望能够设置它的颜色和厚度,就像<hr>
标签允许我一样。使用JS画一条水平线
我有一个网站,我需要做这样的<script
>标签内(连同一些相关的代码)。我不能使用<hr>
,因为我的一些用户没有启用JS;所以对于他们来说,<script>
标签内容都不会显示,但<hr>
仍然会显示(我不希望发生这种情况)。
处理问题,第一:
我不能用
<hr>
,因为我的一些用户没有启用JS;所以对于他们来说,<script>
标签内容都不会显示,但<hr>
仍然会显示(我不希望发生这种情况)。
可以在JavaScript中的类添加到您的<html>
元素(classList
如果你不需要IE 9支持):
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的网页上只是创建一个HR元素,这是如下:
elem = document.createElement("hr"); //this will create a new element
/* Use setAttribute to define the property and values you'd like give the element */
elem.setAttribute("width", "100px");
/* Then you'll need to add the element to the page */
document.body.appendChild(elem);
您可以使用标准的<hr>
元素与一些CSS从无脚本的用户隐藏。
看看这个:http://arsdnet.net/testo.html有和没有JavaScript。下面的代码:
<!DOCTYPE html>
<html>
<head>
<title>Noscript example</title>
<style>
/* this css is used by people with and without javascript */
/* a <link> tag would work as well, of course */
</style>
<noscript>
<style>
/* this is only visible by people without JS enabled */
hr {
display: none;
}
</style>
</noscript>
<script>
/* And this script only runs with JS (obviously) so by adding
a class name to the root element (<html>), we can also detect
it in CSS....
*/
document.documentElement.className += " with-js";
</script>
<style>
/* ...meaning we can target it with CSS like this too: */
html.with-js hr {
color: red;
}
</style>
</head>
<body>
Hi, before hr
<hr />
After hr
</body>
</html>
的<noscript>
标签是有效的HTML从waaaaay回来作品无处不在。它内部的任何内容仅对没有脚本支持的人员可见,并且可以包含任何内容:备用html,链接标记,样式标记,任何内容。
通过在其中添加样式标签,我可以使用CSS隐藏不希望非脚本用户可以看到的元素。
那么我只需在它下面写一个普通的HTML,这对所有的用户来说都是可见的 - 没有什么特别的。然后,使用<noscript><style>
我将它修改为没有脚本的人作为特例。
有时顺便说一句,你想只显示东西脚本的用户,而不是只隐藏nonscript用户的东西。最简单的方法是使用javascript在html元素上粘贴一个类,然后使用CSS来定位该类名称后代。样本中接下来的几行显示。再次,您编写普通的HTML,然后在事实后修改它,但这次使用<script>
的组合来添加一个类并将<style>
作为目标。
所以用JS看这个页面,你会看到一个红色的小时。没有JS,hr不会出现。
你有没有考虑在'
@ AdamD.Ruppe:道歉,我其实不知道。你可以补充说,作为答案? – Sophia111
我用样品中的几种技术回答。一般来说,我总是尝试编写纯粹的,简单的HTML,它适用于我想要的,然后使用javascript,CSS或noscript元素对其进行自定义,以涵盖特殊情况。这样做往往会提供可读的源代码和良好的兼容性 - 基本的html适用于几乎所有人! –