通过javascript动态添加CSS到页面 [英] Dynamically add css to page via javascript
本文介绍了通过javascript动态添加CSS到页面的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在做一个小部件将被添加到外部网站,我做了一个页面,生成CSS为他们风格(文本颜色,背景颜色,字体大小等)。我最终得到一个textarea填充css供他们复制/粘贴到他们的网站。
有一种方法来添加这个CSS到当前页面,如果要添加css文本,
b p $ p>
var style = document.createElement('style')
style.type ='text / css'
style.innerHTML ='content'
.getElementsByTagName('head')[0] .appendChild(style)
文件
var link = document.createElement('link')
link.setAttribute('rel','stylesheet ')
link.setAttribute('type','text / css')
link.setAttribute('href','css / my.css')
document.getElementsByTagName ')[0] .appendChild(link)
I'm making a widget that will be added to external websites, and I have made a page that generates css for them to style it (text color, background color, font size, etc). I end up with a textarea filled with css for them to copy/paste to their website.
Is there a way to add this css to the current page in order to have a live preview?
解决方案
if you want to add css text
var style = document.createElement('style')
style.type = 'text/css'
style.innerHTML = 'content'
document.getElementsByTagName('head')[0].appendChild(style)
if you want to add css file
var link = document.createElement('link')
link.setAttribute('rel', 'stylesheet')
link.setAttribute('type', 'text/css')
link.setAttribute('href', 'css/my.css')
document.getElementsByTagName('head')[0].appendChild(link)
这篇关于通过javascript动态添加CSS到页面的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文