简体   繁体   English

不知道为什么.css()不会更改div质量

[英]not sure why .css() wont change div qualities

I'm trying to use jQuery to change the value of the div 'dog' from blue (CSS) to red (javascript css code), but the javascript seems to not be functioning. 我正在尝试使用jQuery将div“狗”的值从蓝色(CSS)更改为红色(javascript CSS代码),但是javascript似乎无法正常工作。 CSS, JavaScript and jQuery are all linked properly (have checked). CSS,JavaScript和jQuery均已正确链接(已检查)。

HTML CODE: HTML代码:

 <!DOCTYPE html>
 <html>
  <head>
   <title></title>
   <link rel="stylesheet" type="text/css" href="style.css">
   <script  src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>       
   <script type="text/javascript" src="jquery-3.2.0.min.js"></script>
   <script type="text/javascript" src="script.js"></script>
  </head>
  <body>
   <div id="dog"></div>
  </body>
 </html>

CSS CODE: CSS代码:

#dog {
  background-color: blue;
  height: 200px;
  width: 200px;
}

JAVASCRIPT (jQuery) CODE: JAVASCRIPT(jQuery)代码:

$("#dog").css("background-color", "red");

but the javascript seems to not be functioning. 但是javascript似乎无法正常运行。 CSS, JavaScript and jQuery are all linked properly (have checked). CSS,JavaScript和jQuery均已正确链接(已检查)。

Ensure that you encapsulate the javascript within a $( document ).ready() . 确保将javascript封装在$( document ).ready() This should solve the problem if the script is loaded in the head element, where the HTML document has not been loaded fully yet. 如果脚本已加载到head元素中,而HTML文档尚未完全加载,则应该可以解决该问题。

However, an alternative solution is to use the script tag within the body element. 但是,另一种解决方案是在body元素中使用script标签。

Example: 例:

 <!DOCTYPE html> <html> <head> <title></title> <link rel="stylesheet" type="text/css" href="style.css"> <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery .min.js"></script> <script type="text/javascript" src="jquery-3.2.0.min.js"></script> <script type="text/javascript" src="script.js"></script> <style> #dog { background-color: blue; height: 200px; width: 200px; } </style> </head> <body> <div id="dog"></div> <script> $("#dog").css("background-color", "red"); </script> </body> </html> 

do this in your js file - 在您的js文件中执行此操作-

window.onload = function () {
    $("#dog").css("background-color", "red");
}

The reason is this - 原因是这样的-

window.onload - it is called after all DOM, JS files, Images, Iframes, Extensions and others completely loaded. window.onload-在所有DOM,JS文件,图片,iframe,扩展名和其他文件完全加载后调用。 This is equal to $(window).load(function() {}); 等于$(window).load(function() {});

As you have a seperate js file, and you want the style to be changed when the page is loaded, so you have to do this. 由于您有单独的js文件,并且希望在加载页面时更改样式,因此必须执行此操作。

For more understanding, you can refer this - Difference between onload and window.onload 要了解更多信息,可以参考此内容-onload和window.onload之间的区别

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

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