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

操作表单元素属性




自定义属性


输出结果为


相关推荐
C澒2 小时前
多场景多角色前端架构方案:基于页面协议化与模块标准化的通用能力沉淀
前端·架构·系统架构·前端框架
崔庆才丨静觅2 小时前
稳定好用的 ADSL 拨号代理,就这家了!
前端
江湖有缘2 小时前
Docker部署music-tag-web音乐标签编辑器
前端·docker·编辑器
恋猫de小郭3 小时前
Flutter Zero 是什么?它的出现有什么意义?为什么你需要了解下?
android·前端·flutter
崔庆才丨静觅10 小时前
hCaptcha 验证码图像识别 API 对接教程
前端
passerby606111 小时前
完成前端时间处理的另一块版图
前端·github·web components
掘了11 小时前
「2025 年终总结」在所有失去的人中,我最怀念我自己
前端·后端·年终总结
崔庆才丨静觅11 小时前
实用免费的 Short URL 短链接 API 对接说明
前端
崔庆才丨静觅11 小时前
5分钟快速搭建 AI 平台并用它赚钱!
前端
崔庆才丨静觅12 小时前
比官方便宜一半以上!Midjourney API 申请及使用
前端