使用jquery向未知页面添加CSS节点
Adding a CSS node into unknown pages using jquery
如何使用jquery将<link>
节点添加到页面的<head>
部分?如果元素已经存在,则不应该添加两次。
我需要添加这个CSS文件,因为它为我的搜索函数引入了额外的样式。这个jquery荧光笔需要.highlight
类被添加到页面,所以高光看起来是黄色的。
Edit:我可以这样做,但是它不会检查元素是否已经添加。
$('head').append('<link rel="stylesheet" href="style2.css" type="text/css" />');
详细信息在实时演示的源代码中进行了注释:PLUNKER和下面的代码片段:
/* This script can be placed before the closing </body> tag as is or wrapped in a declared function then called. (ex. function init() {....}) */
// Reference the <head>
var head = document.getElementsByTagName('head')[0];
// This will find a `('link` element with a `[href` attribute with the value ending `$=` with `"style2.css"` `]')`
var style2 = document.querySelector('link[href$="style2.css"]');
// create a <link>
var link = document.createElement('link');
// Add a href attribute with the value of "style3.css" to the new <link>
link.href = 'style3.css';
// Add a rel attribute with the value of 'stylesheet'
link.setAttribute('rel', 'stylesheet');
// If <link href='style2.css'... already exists, then quit, else add the new <link> as the last child of the <head>
var inject = (style2) ? false : head.appendChild(link);
return inject;
<!doctype html>
<html>
<head>
<link hraf='style.css' rel='stylesheet'>
<link href='style2.css' rel='stylesheet'>
</head>
<body>
<p>Use devtools and find the <head>. You should see the following*:</p>
<pre><code>
<head>
<link rel="stylesheet" href="style1.css">
<!--link rel="stylesheet" href="style2.css"-->
<link rel="stylesheet" href="style3.css">
</head>
</code></pre>
*The code displayed above is always green.
<script src="init.js"></script><!--script wrapped in a declared function in an external js file-->
<script>
init(); //Call init() right before the body closing tag or place the whole script here without being wrapped in a declaritive function.
</script>
</body>
</html>
相关文章:
- 如何添加CSS&JavaScript进入Windows窗体应用程序C#.net
- 对于每个json结果,使用类jquery添加css
- 为未标记的文本添加CSS样式
- 在WordPress中使用JavaScript在html元素上添加css类
- jQuery检查CSS宽度是否大于0,然后添加CSS属性
- 单击禁用的按钮添加 CSS
- 在 Twig Child 中添加 CSS 和 JavaScript
- 更改现有的css属性,并通过删除或添加css元素来使用它
- Ember.js为特定的模型id添加css类
- 我可以用添加css吗!重要的是,只使用jquery
- Regex用于添加CSS类
- 如何在一个表的输入中搜索一组特定的值,而不是另一个表's id(s)值以添加css
- 使用JQuery添加css属性悬停
- 通过程序添加CSS渐变作为背景图像
- 使用JS添加CSS规则
- 如何为Fabric.js中的文本添加CSS属性
- IE7/8未添加css属性'top'动态地作为内联样式
- 通过jquery损坏的旋转木马添加css样式
- Node.js Express应用程序:如果存在cookie,则从服务器端向元素添加CSS类
- 添加css转换时间以使用javascript切换类