简体   繁体   English

通过Javascript添加CSS

[英]Adding CSS via Javascript

I am trying to add some CSS styling (in addition to the styles already in place) via Javascript (simply because i do not have access to the main CSS file) 我试图通过Javascript添加一些CSS样式(除了已经存在的样式外)(原因是我无法访问主CSS文件)

http://jsfiddle.net/pbPyU/ http://jsfiddle.net/pbPyU/

HTML: HTML:

<a class='store-locator-button'>replace me</a>

JAVASCRIPT: JAVASCRIPT:

$(function() {
$('.store-locator-button').addClass('tempstorebutton');
$("a.store-locator-button").each(function(index,el){
    $(el).text('BUSCAR UNA TIENDA');
  }); 
});

CSS: CSS:

.tempstorebutton{padding:5px; color:#fa5dae;}

It works fine in JSfiddle, but not on my site. 它在JSfiddle中工作正常,但在我的网站上却不行。 Any suggestions? 有什么建议么?

The order in which CSS is applied is important. CSS的应用顺序很重要。 You should add your JavaScript code at the bottom of the page to make sure it gets applied in case some other styles are already applied before hand. 您应该在页面底部添加JavaScript代码,以确保在应用某些其他样式之前应用该代码。 Try !important property too in case your CSS is overriden. 也可以尝试!important属性,以防您的CSS被覆盖。

I would recommend having your own css file being rendered after the one you want to override. 我建议您在要覆盖的CSS文件之后渲染自己的CSS文件。

Then you should add those classes that you want to override on your css file with the styles that you want. 然后,应使用所需的样式在CSS文件中添加要覆盖的那些类。 Otherwise it's a frustrating path you should avoid. 否则,这是您应避免的令人沮丧的道路。

!important declarations should not be used unless they are absolutely necessary. 除非绝对必要,否则不要使用!important声明。

Every browser has default css settings. 每个浏览器都有默认的CSS设置。 You must override css. 您必须覆盖CSS。

  • one approach is to reset css: reset css example 一种方法是重置CSS: 重置CSS示例
  • another approach is to override only the parts you need css with !important 另一种方法是使用!important覆盖仅需要CSS的部分

keep in mind that in css the more specific is on a higher priority to render 请记住,在CSS中,渲染的优先级越高

you can also try to check if the css changes you make appear with changing the css code in firefox firebug or google chrome developer or your browser debugging interface and than you can see if your css tweeks work for real or not. 您还可以尝试检查您所做的css更改是否随在firefox firebug或google chrome开发人员或浏览器调试界面中更改css代码而出现,然后您可以查看css tweeks是否真正起作用。

you can also try to give the class a different name. 您也可以尝试为课程指定其他名称。

hope it helps feel free to correct and edit anyone 希望它可以帮助您随时纠正和编辑任何人

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM