实现图片点击切换、通过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>

操作表单元素属性




自定义属性


输出结果为


相关推荐
JarvanMo几秒前
Bitrise 自动化发布 Flutter 应用终极指南(二)
前端
『 时光荏苒 』19 分钟前
网页变成PDF下载到本地
前端·javascript·pdf·网页下载成
亿元程序员26 分钟前
逃离鸭科夫5人2周1个亿,我们可以做一个鸡科夫吗?
前端
十一.3661 小时前
37-38 for循环
前端·javascript·html
波诺波1 小时前
环境管理器
linux·前端·python
San30.1 小时前
深入理解浏览器渲染流程:从HTML/CSS到像素的奇妙旅程
前端·css·html
IT_陈寒1 小时前
5个Python 3.12新特性让你的代码效率提升50%,第3个太实用了!
前端·人工智能·后端
周杰伦_Jay1 小时前
【Python Web开源框架】Django/Flask/FastAPI/Tornado/Pyramid
前端·python·开源
艾小码1 小时前
为什么你的JavaScript代码总是出bug?这5个隐藏陷阱太坑了!
前端·javascript
辻戋3 小时前
从零实现React Scheduler调度器
前端·react.js·前端框架