ログイン
問題1

liタグの横幅を足してみよう

アイコン画像

問題1:liタグの横幅を足してみよう

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¥
            

コメントのアイコン解説

何かの合計を計算するとなった場合、ループ処理が走ることが多いです。

そしてループ中に条件を加えると言うのも良くあるパターンです。

この問題を3分程度で解ければ上級者と言って良いでしょう。
ログインして解答を見る
完了にする!
twitterのアイコン
活動記録をTweetする
1.JavaScriptでできること
続きの動画を見たい方は公式LINEから「JavaScript」と送信すると動画が見れます。
LINEの友達追加でお役立ち動画をGET!!
LINEの友達追加でお役立ち動画をGET!!

閉じる