编程练习打卡
来源:1-19 自由编程
浅梦sky
2021-01-07 23:10:32
我增加了两个地方:
(1) 蓝色和绿色的div块,点击一下增加背景,再点击一下去掉背景和文字
(2) 输入颜色首字母处:当把输入框中输入的值都删除掉之后,背景色和文字都去掉
1、html代码:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>1-19编程练习</title>
<link rel="stylesheet" type="text/css" href="css/1-19.css"/>
<script src="js/jquery-3.5.1.js" type="text/javascript"></script>
<script src="js/1-19.js" type="text/javascript" charset="utf-8"></script>
</head>
<body>
<h2>请选择背景颜色</h2>
<div class="color_div">
<div id="blue" class="div1">蓝色</div>
<div id="green" class="div1">绿色</div>
</div>
<div class="div2" id="bg"></div>
<div class="div3">
<label>输入颜色首字母:</label>
<input type="text" name="color">
</div>
</body>
</html>
2、css代码:
.div1 {
float: left;
width: 50px;
line-height: 30px;
background-color: lightgray;
margin-left: 10px;
text-align: center;
vertical-align: middle;
cursor: pointer;
}
.div2{
width: 300px;
height: 300px;
border: solid gray 1px;
margin-top: 60px;
color: red;
}
3、js代码
/*加载页面元素*/
$(function () {
// 弹窗
alert("欢迎来到颜色设置页面");
// 获取需要设置背景的div块
var div2 = $(".div2");
// 获取颜色输入框
var color_input = $("input[name='color']");
// 标识是否有蓝色背景,false表示没有
var hadBlueColor = false;
// 标识是否有绿色色背景,false表示没有
var hadGreenColor = false;
// 获取蓝色div块,并设置背景色和字体颜色
$(".div1[id='blue']").click(function () {
// 判断如果有蓝色,则去掉背景和文字
if (hadBlueColor){
div2.css("backgroundColor","white");
div2.text("");
hadBlueColor = false;
return;
}
// 设置背景和字体颜色
div2.css({
"backgroundColor": "blue",
"color": "red"
});
div2.text("蓝色的背景");
// 有蓝色背景
hadBlueColor = true;
});
// 获取蓝色div块,并设置背景色和字体颜色
$("div#green").click(function () {
// 判断如果有绿色,则去掉背景和文字
if (hadGreenColor){
div2.css("backgroundColor","white");
div2.text("");
hadGreenColor = false;
return;
}
// 设置背景和字体颜色
div2.css({
"backgroundColor": "green",
"color": "red",
"fontStyle": "italic",
"fontWeight": "bold"
});
div2.text("绿色的背景");
// 有绿色背景
hadGreenColor = true;
});
// 给输入框绑定键盘事件
color_input.keyup(function (event) {
if (event.keyCode == 71){
// 获取输入框的第一个字母
var firstValue = $(this).val().substring(0,1);
//console.log(firstValue);
if (firstValue == "G" || firstValue == "g") {
// 设置背景和字体颜色
div2.css({
"backgroundColor": "green",
"color": "red",
"fontStyle": "italic",
"fontWeight": "bold"
});
div2.text("绿色的背景");
}
}
if (event.keyCode == 66){
// 获取输入框的第一个字母
var firstValue = $(this).val().substring(0,1);
//console.log(firstValue);
if (firstValue == "B" || firstValue == "b") {
// 设置背景和字体颜色
div2.css({
"backgroundColor": "blue",
"color": "red"
});
div2.text("蓝色的背景");
}
}
if (event.key == "Backspace"){
// 获取输入框的值
var input_value = $(this).val();
if (input_value == "" || input_value.length == 0){
div2.css("backgroundColor","white");
div2.text("");
}
}
});
});
1回答
好帮手慕小班
2021-01-08
同学你好,经测试运行同学贴出的代码,是没有问题的,同学根据自己的想法也完成了对应的效果
很棒~继续加油
祝学习愉快!