[英]How To Change stylesheet by javascript
I've try's to get element and change the style by content: if element content is English
then CSS should be ltr.css
else if
element content is Persian
the css should be 'rtl.css' here is what i have我尝试获取元素并按内容更改样式:如果元素内容是
English
,那么 CSS 应该是ltr.css
else if
元素内容是Persian
ZC7A628CBA22E28EB17B5F5C6AE2A26 应该是什么
addEventListener("DOMContentLoaded", () => { var lang = document.getElementById('languageChooser').innerHTML; if(lang == 'Persian'){ document.querySelector('#style1').setAttribute('href', 'rtl.css');; } else if (lang == 'English') { document.querySelector('#style1').setAttribute('href', 'ltr.css');; } })
<a href="" id="languageChooser">Persian</a> <link id="style1" rel="stylesheet" type="text/css" href="ltr.css" />
this is the whole application这是整个应用程序
Using jquery you can definitely swap the css file.使用 jquery 您绝对可以交换 css 文件。 Do this on button click .
在按钮单击时执行此操作。
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<link id="style1" rel="stylesheet" type="text/css" href="ltr.css" />
</head>
<body>
<a href="#" id="languageChooser">Persian</a>
</body>
<script type="text/javascript">
$("#languageChooser").click(function() {
var lang = document.getElementById('languageChooser').innerHTML;
var selector = $('link[href*="ltr.css"]');
if (lang == 'Persian') {
selector.replaceWith('<link href="rtl.css" type="text/css" rel="stylesheet">');
}
});
</script>
</html>
You need to use ==
to compare.您需要使用
==
进行比较。 And to use condition in else, you need to use else if
并且要在 else 中使用条件,您需要使用
else if
if(lang == 'Persian'){
el.href = "rtl.css";
} else if (lang == 'English') {
el.href = "ltr.css";
}
You just have to change attribute of link element like this您只需要像这样更改链接元素的属性
document.querySelector('link').setAttribute('href', 'ltr.css');
EDIT编辑
Make sure that your script is executed after loading the document content.确保在加载文档内容后执行您的脚本。 (add
script
tag at the end of the html file, or use defer
script attribute, or use DOMContentLoaded
event. (在 html 文件末尾添加
script
标签,或者使用defer
script 属性,或者使用DOMContentLoaded
事件。
let el = document.querySeletor("#style1");
el.setAttribute("href", (lang == "Persian")? "rtl.css" : "ltr.css");
If I understood correctly you can automatically change style file, by language.如果我理解正确,您可以按语言自动更改样式文件。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.