实现图片点击切换、通过classList修改样式、操作表单元素属性、自定义属性

实现图片点击切换

html 复制代码
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<style>
    * {
        box-sizing: border-box;
    }

    .box {
        background-color: pink;
        width: 200px;
        height: 150px;
        border: 1px solid black;

    }
    #NameBox{
        font-size: 50px;
        text-align: center;
        line-height: 150px;
        color: azure;
    }
</style>

<body>
    <div class="box" id="NameBox"></div>
    <img src="../img/1.jpeg">


    <script>
        const box = document.querySelector('.box')
        const NameBox = document.getElementById('NameBox');
        box.style.width = '400px'

        function getRandom(N, M) {
            return Math.floor(Math.random() * (M - N + 1)) + N
        }

        const img = document.querySelector('img')//获取元素
        const random = getRandom(1, 6)
        img.src = `../img/${random}.jpeg`


        let num = 1;

        function showMessage() {
            num++;
            if (num % 5 === 0) {
                img.src = `../img/3.jpeg`
                NameBox.textContent = '图片3';
            } else if (num % 2 === 0) {
                img.src = `../img/2.jpeg`
                NameBox.textContent = '图片2';
            } else {
                img.src = `../img/1.jpeg`
                NameBox.textContent = '图片1';
            }
            console.log(num);
            // img.src = `../img/${num}.jpeg`

            

        }
        img.addEventListener('click', showMessage)//img
    </script>
</body>

</html>

通过classList修改样式

html 复制代码
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<style>
    .box{
        width: 200px;
        height: 200px;
        color: #333;
    }
    .active{
        color: red;
        background-color: pink;
    }
</style>
<body>
    <div class="box">文字</div>
    <script>
        //通过classList添加
        //获取元素
        const box = document.querySelector('.box')
        //修改样式 
        //追加类 add() 类名不加点 并且是字符串
        box.classList.add('active')
        //删除类 remove() 类名不加点 并且是字符串
        box.classList.remove('box')
        //切换类 toggle() 有就删掉,没有就加上
        box.classList.toggle('active')

    </script>
</body>
</html>

操作表单元素属性




自定义属性


输出结果为


相关推荐
天天扭码7 小时前
如何实现流式输出?一篇文章手把手教你!
前端·aigc·ai编程
前端 贾公子8 小时前
vue移动端适配方案 === postcss-px-to-viewport
前端·javascript·html
GISer_Jing9 小时前
AI营销增长:4大核心能力+前端落地指南
前端·javascript·人工智能
明远湖之鱼9 小时前
一种基于 Service Worker 的渐进式渲染方案的基本原理
前端
前端小端长10 小时前
Vue 中 keep-alive 组件的原理与实践详解
前端·vue.js·spring
FeelTouch Labs10 小时前
Nginx核心架构设计
运维·前端·nginx
雪球工程师团队10 小时前
别再“苦力”写后台,Spec Coding “跑” 起来
前端·ai编程
m0_4711996310 小时前
【场景】前端怎么解决离线收银、数据同步异常等场景问题
前端·javascript
Curvatureflight10 小时前
前端性能优化实战:从3秒到300ms的加载速度提升
前端·人工智能·性能优化