jquery怎么动态加style属性

jquery怎么动态加style属性,第1张

使用jQuery css() 方法

css() 方法设置或返回被选元素的一个或多个样式属性

语法:

css("propertyname","value")

1.当value参数不存在时为获取该属性

2.当value参数存在时为设置该属性。

$("p").css("background-color")//获取p元素的背景颜色

$("p").css("background-color","yellow")//设置p元素的背景颜色为黄色

style也可以看做普通的HTML节点,因此其创建方法与jQuery创建普通元素的方法相同,关键代码:

$("<style></style>").text("div#test{color:red}").appendTo($("head"))

下面实例演示——点击按钮创建新的style样式:

1、HTML结构

<div id="test">这是示例的DIV</div>

<input type="button" value="创建新的<style>">

2、jQuery代码

$(function(){

$("input[type='button']").click(function() {

$("<style id='test_style'></style>").text("div#test{color:red}").appendTo($("head"))

$("div#test").html($("div#test").text() + "<br>" + $("#test_style").text())

})

})

3、效果演示

   if (window.ActiveXObject) { /*ie*/

                window.style = ".b{color:#ccc}"

                document.createStyleSheet("javascript:style")

            } else {

                var style = document.createElement('style')

                style.type = 'text/css'

                style.innerHTML = ".b{color:#ccc}"

                document.getElementsByTagName('HEAD').item(0).appendChild(style)

            }


欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/bake/7990735.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2023-04-12
下一篇 2023-04-12

发表评论

登录后才能评论

评论列表(0条)

保存