Vue入门 Demo10 Vue中的样式绑定(实现页面展示的文字点击后变颜色)

Vue入门 Demo10 Vue中的样式绑定(实现页面展示的文字点击后变颜色)

<!DOCTYPE html>
<html lang="en"> 
    <head> 
        <meta content="text/html; charset=utf-8" /> 
        <title>计Vue中的样式绑定</title> 
        <script src="./vue.js"></script>
        <style>
            .activated {
                color: red;
            }
        </style>
    </head> 
    <body>
    <!-- 点击hello world颜色变为一种颜色,再次点击时将变为原来颜色,再次点击变为刚刚的颜色.. -->
    <!-- 1.使用class对数据对象进行绑定 -->
       <!-- <div id="app">  
            <div @click="handerDivClick"
                 :class="{activated: isActivated}"
               >
               hello world
            </div>
       </div> -->

       <!-- 方法一.class设置为数组开始 -->
       <!-- <div id="app">  
            <div @click="handerDivClick"
                :class= "[activated]"
            >
            hello world
            </div>
        </div>

       <script>
           var vm = new Vue({
                el: "#app",
                data: {
                    activated: "", 
                },
                methods: {
                    handerDivClick: function(){
                        // if(this.activated === "activated"){
                        //     this.activated = "";
                        // }else{
                        //     this.activated = "activated";
                        // }
                        //三元运算符
                        this.activated = this.activated === "activated" ? 
                           "" : "activated";
                    }
                }
                
           })
       </script> -->
       <!-- 方法一.class设置为数组结束 -->

       <!-- 方法二:div中设置style标签开始,style后面也可以定义为数组 -->
       <div id="app">  
            <div :style="styleObj"
                 @click="handerDivClick"
            >
             hello world
        </div>

        <script>
            var vm = new Vue({
                el: "#app",
                data: {
                    styleObj: {
                        color: "black",
                    }
                },
                methods: {
                    handerDivClick: function(){
                        this.styleObj.color = this.styleObj.color === "black" ? "red" : "black";
                    }
                }
            })
        </script>
        <!-- 方法二:div中设置style标签结束 -->
    </div>
    </body> 
</html>
发布了45 篇原创文章 · 获赞 2 · 访问量 5179

猜你喜欢

转载自blog.csdn.net/qq_36778310/article/details/104696775