企业🤖AI智能体构建引擎,智能编排和调试,一键部署,支持私有化部署方案 广告
## js点击事件 >效果如图 > (忽略左边的黑线) ![](https://box.kancloud.cn/d1084ce53de1a11576dcc3f69761ffa0_1174x608.gif) >html代码 ``` <p class="title">请为下面的div设置样式: <span id="click">点击设置</span></p> <div id="test"></div> <div id="setting"> <p>请选择背景色: <span id="red">红</span> <span id="yellow">黄</span> <span id="blue">蓝</span> </p> <p>请选择宽(px): <span id="w-2">200</span> <span id="w-3">300</span> <span id="w-4">400</span> </p> <p>请选择高(px): <span id="h-2">200</span> <span id="h-3">300</span> <span id="h-4">400</span> </p> <span id="reset">恢复</span> <span id="makesure">确定</span> </div> ``` >css代码 ``` * { margin: 0; padding: 0; } .title { font-size: 25px; font-weight: bold; } .title>span { padding: 5px; background: red; color: #fff; cursor: pointer; } #test { width: 50px; height: 50px; margin-top: 40px; border: 3px solid #ddd; } #setting { position: fixed; display: none; top: 20%; right: 40%; padding: 10px; font-size: 20px; border: 5px solid #ccc; } #setting>p { margin-bottom: 17px; } #setting span { margin: 0 3px; padding: 3px 10px; cursor: pointer; } #setting span:hover { background-color: aquamarine; } #setting>span { background-color: cadetblue; color: #fff; } #setting>p>span { padding: 3px 10px; background-color: #ddd; } ``` >js代码 ``` window.onload = function(){ /*封装$*/ var $ = function(id){ return document.getElementById(id); } var click = $("click"); click.onclick = function(){setting.style.display = "block";} /*建立设置颜色,宽,高的函数*/ function c_color(id, color){ var dom = document.getElementById(id); dom.style.backgroundColor = color; } function w_width(id, width){ var dom = document.getElementById(id); dom.style.width = width + "px"; } function h_height(id, height){ var dom = document.getElementById(id); dom.style.height = height +"px"; } /*为各个按钮设置点击动作*/ $("red").onclick = function(){c_color("test", "red");} $("yellow").onclick = function(){c_color("test", "yellow");} $("blue").onclick = function(){c_color("test", "blue");} $("w-2").onclick = function(){w_width("test", 200);} $("w-3").onclick = function(){w_width("test", 300);} $("w-4").onclick = function(){w_width("test", 400);} $("h-2").onclick = function(){h_height("test", 200);} $("h-3").onclick = function(){h_height("test", 300);} $("h-4").onclick = function(){h_height("test", 400);} $("reset").onclick = function(){ $("test").style.width = 50 + "px"; $("test").style.height = 50 + "px"; $("test").style.backgroundColor = "#fff"; } $("makesure").onclick = function(){ $("setting").style.display = "none"; } } ``` ---- 整个demo已上传至[github](https://github.com/MrXuxu/H5_demo/tree/master/JS%E7%82%B9%E5%87%BB%E4%BA%8B%E4%BB%B6)