
問題1:liタグの横幅を足してみよう
liタグの横幅の合計を計算し
.anser の中に表示させてください。
ただし条件があります。
3番目のliタグの横幅は含まないでください。
.anser の中に表示させてください。
ただし条件があります。
3番目のliタグの横幅は含まないでください。
あらかじめエディタに書くコード
<div class="anser"></div>
<ul>
<li></li>
<li></li>
<li></li>
<li></li>
<li></li>
</ul>
¥HTML¥
.anser{
text-align: center;
font-weight: bold;
font-size: 30px;
margin: 300px 0 20px 0;
}
ul{
width: 1000px;
margin: 0 auto 0 auto;
display: flex;
list-style: none;
}
li{
height: 100px;
background-color: #1d4177;
margin-right: 10px;
}
li:nth-child(1){width: 200px;}
li:nth-child(2){width: 120px;}
li:nth-child(3){width: 300px;}
li:nth-child(4){width: 80px;}
li:nth-child(5){width: 160px;}
¥CSS¥
期待する画面

解答ソースコード
$(function(){
let li_total = 0;
$('li').each(function(index, el) {
if(index !== 2){
li_total += $(el).width();
$('.anser').text(li_total);
}
});
});
¥JavaScript¥
<!DOCTYPE html>
<html lang="">
<head>
<meta charset="UTF-8">
<title>タイトル</title>
<link href="https://fonts.googleapis.com/css?family=Kosugi+Maru&display=swap" rel="stylesheet">
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">
<meta name="viewport" content="width=device-width">
<style>
.anser{
text-align: center;
font-weight: bold;
font-size: 30px;
margin: 300px 0 20px 0;
}
ul{
width: 1000px;
margin: 0 auto 0 auto;
display: flex;
list-style: none;
}
li{
height: 100px;
background-color: #1d4177;
margin-right: 10px;
}
li:nth-child(1){width: 200px;}
li:nth-child(2){width: 120px;}
li:nth-child(3){width: 300px;}
li:nth-child(4){width: 80px;}
li:nth-child(5){width: 160px;}
</style>
</head>
<body>
<div class="anser"></div>
<ul>
<li></li>
<li></li>
<li></li>
<li></li>
<li></li>
</ul>
<script
src="https://code.jquery.com/jquery-3.4.1.js"
integrity="sha256-WpOohJOqMqqyKL9FccASB9O0KwACQJpFTUBLTYOVvVU="
crossorigin="anonymous"></script>
</body>
</html>
¥HTML¥
完了にする!
活動記録をTweetする
1.JavaScriptでできること
そしてループ中に条件を加えると言うのも良くあるパターンです。
この問題を3分程度で解ければ上級者と言って良いでしょう。