简体   繁体   English

我想使用 Jquery 向我的 html 元素添加更多 css 属性意味着我不想删除前一个,只是简单地向它添加更多

[英]I want to add more css property to my html element using Jquery means I dont want to remove the previous one just simply add more to it

Index.html索引.html

<html>
<head>
<script
      src="https://code.jquery.com/jquery-3.4.1.js"
      integrity="sha256-WpOohJOqMqqyKL9FccASB9O0KwACQJpFTUBLTYOVvVU="
      crossorigin="anonymous"></script>
<!-- jquery-3.4.1.min -->
<script type="text/javascript" src="custom.js"></script>
</head>
<body>
<div class="epic" style="color:red">hello this is title</div>
<div>hello this is title</div>
<input type="button" placeholder="click it" value="click">
</body>
</html>

custom.js自定义.js

$( document ).ready(function($){       
   $(":button").click(function(){    
    $(".epic").attr("style","font-size:100px");    
   });        
});

Now What I want Is when I click the button than I should be able to give the font-size that I want but keep the previous color red also .现在我想要的是当我点击按钮时,我应该能够给出我想要的字体大小,但也保持以前的颜色为红色。 The code that I have written makes the font 100 but color is gone ,so Is there any way to keep the color and still be able to modify the font.我写的代码使字体为 100,但颜色消失了,所以有什么办法可以保持颜色并且仍然能够修改字体。

You can use .css() to set the particular style property ( font-size ):您可以使用.css()来设置特定的样式属性( font-size ):

 $( document ).ready(function(){ $(":button").click(function(){ $(".epic").css("font-size", "100px"); }); });
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <div class="epic" style="color:red">hello this is title</div> <div>hello this is title</div> <input type="button" placeholder="click it" value="click">

Use .css method instead.改用.css方法。 And pass a object of CSS properties.并传递一个 CSS 属性对象。 When you will call it again, it will just add the new properties to existing one.当您再次调用它时,它只会将新属性添加到现有属性中。

In your solution, you are overwriting the complete style attribute everytime.在您的解决方案中,您每次都覆盖完整的style属性。 So it is removing the older properties.所以它正在删除旧的属性。

 $(document).ready(function() { $(":button").click(function() { $(".epic").css({ "font-size": "50px", "background-color": "blue" }); $(".epic").css({ "color":"white" }); }); });
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <div class="epic" style="color:red">title</div> <div>hello this is title</div> <input type="button" placeholder="click it" value="click">

You could use the jQuery addClass() method to keep the original CSS class and add a new one:您可以使用 jQuery addClass()方法保留原始 CSS 类并添加一个新类:

$("button").click(function(){
  $(".epic").addClass("clicked");
});

And in the CSS:在 CSS 中:

.clicked {
    font-size: 50px;
}

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

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