HEAD FIRST HTML5 PROGRAMMING 中文版_ 笔记

162 阅读6分钟

Snipaste_2021-04-15_18-54-37.png

1.0 DOM

<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
    <script>
      function addSongs() {;
        var song1 = document.getElementById("song1");//使用getElementByld来调用'song1'这个元素
        var song2 = document.getElementById("song2");
        var song3 = document.getElementById("song3");
        song1.innerHTML = "Blue Suede Strings,by Elvis pagely";//使用song1元素innerHTML属性改变元素的内容,
        song2.innerHTML = "Great Objects on Fire.by Johnny JavaScript";
        song3.innerHTML = "I Code the Line.by johnny Javascript";
      }

      window.onload = addSongs;//这里将window.onload属性的值设置为这个函数名,表示页眉完成加载时要执行adsongs中的代码
      
    </script>
  </head>
  <body>
    <h1>My awesome playlist</h1>
    <ul id="playlist">
      <li id="song1"></li>
      <li id="song2"></li>
      <li id="song3"></li>
    </ul>
  </body>
</html>

写一个随机取词的程序

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=h1, initial-scale=1.0" />
    <title>Document</title>
    <script>
      function makePhrase() {
        var words1 = ["爸爸", "妈妈", "爷爷", "奶奶", "叔叔", "婶婶"];
        var words2 = ["外公", "外婆", "舅舅", "舅妈", "表弟", "表妹"];
        var words3 = ["大哥", "二哥", "四弟", "五妹", "六弟", "六妹"];

        var rand1 = Math.floor(Math.random() * words1.length); //数组length属性获取整数
        var rand2 = Math.floor(Math.random() * words2.length);
        var rand3 = Math.floor(Math.random() * words3.length);

        var phrase = words1[rand1] + "" + words2[rand2] + "" + words3[rand3];
        var phraseElement = document.getElementById("phrase"); //调用
        phraseElement.innerHTML = phrase; //修改
      }
      window.onload = makePhrase; //加载DOM,运行函数
    </script>
  </head>
  <body>
    <h1>随机取词</h1>
    <p id="phrase"></p>
  </body>
</html>

小计:从array删除一个元素,myarray[2]=null.length不变

2 写一个添加歌曲的练习

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>添加歌单</title>
    <script src="playlist_store.js"></script>
    <script src="playlist.js"></script>
    <link rel="stylesheet" href="playlist.css">

</head>

<body>
    <input type="text" id="songTextInput" size="40" placeholder="Song name">
    <input type="button" id="addButton" value="Add Song">
    <ul id="playlist">
    </ul>
</body>

</html>



/* playlist.css */

body {
	font-family: arial, sans-serif;
}

ul#playlist {
	border: 1px solid #a9a9a9;
	-webkit-border-radius: 5px;
	-moz-border-radius: 5px;
	border-radius: 5px;
	margin-top: 10px;
	padding: 0px;
	list-style-type: none;
}

ul#playlist li {
	border-bottom: 1px solid #a9a9a9;
	padding: 10px;
	background-image: -webkit-gradient(linear, left top, left bottom, from(#f9f9f9), to(#e3e3e3));
    background-image: -moz-linear-gradient(#f9f9f9, #e3e3e3);
    background-image: -ms-linear-gradient(#f9f9f9, #e3e3e3);
    background-image: -o-linear-gradient(#f9f9f9, #e3e3e3);
    background-image: -webkit-linear-gradient(#f9f9f9, #e3e3e3);
    background-image: linear-gradient(#f9f9f9, #e3e3e3);
}

ul#playlist li:last-child {
	-webkit-border-bottom-right-radius: 5px;
	-webkit-border-bottom-left-radius: 5px;
	-moz-border-radius-bottomright: 5px;
	-moz-border-radius-bottomleft: 5px;
	border-bottom: none;
	border-bottom-right-radius: 5px;
	border-bottom-left-radius: 5px;
}
ul#playlist li:first-child {
	-webkit-border-top-right-radius: 5px;
	-webkit-border-top-left-radius: 5px;
	-moz-border-radius-topright: 5px;
	-moz-border-radius-topleft: 5px;
	border-top-right-radius: 5px;
	border-top-left-radius: 5px;
}


//1.点击事件
window.onload = init;//页面完全加载时才会调用并执行这个函数
function init() {
    var button = document.getElementById("addButton");//调用getElementById,得到这个按钮
    button.onclick = handleButtonClick;//把按钮onclick设置为这个函数
    loadPlaylist();//加载播放列表,就能看到之前保存的歌曲,load加载
}//在init中设置了一个事件处理程序
function handleButtonClick() {
    alert("button was clicked")
}//当用户点击按钮是,会触发点击事件,并调用这个函数
//2.处理程序
function handleButtonClick() {
    var textInput = document.getElementById("songTextInput");//调用getElementById,得到这个输入文本
    var songName = textInput.value;//声明一个变量被赋值这个的值
    var li = document.createElement("li");//使用createElement创建新元素,append添加,child孩子
    li.innerHTML = songName;//把这个元素内容设置为歌名
    var ul = document.getElementById("playlist");//调用getElementById,找到ul
    ul.appendChild(li)//ul父级li子级作为他的一个孩子
    if (songName == "") {
        alert("please enter a song")
    }
    else {
        alert("Adding" + songName);//弹出
    }
    save(songName);//每次向播放列表增加一首歌时,就会保存起来,save保存
}

思路总结梳理

首先 1.0,建立一个点击事件onclick,找到这个按钮,把按钮的onclick属性设为函数
1.1,加载load歌曲列表
2.0,在设置一个事件处理程序alert(button was clicked")
3.0,处理程序
3.1,给输入文本设置函数,找到输入文本,设置一个变量等于它的输入的值
3.2,创建一个新元素li,li的内部元素innerHTML为歌名songName
3.3,找到UL元素,添加子级元素li
4.0,用if else 判断用户不同的操作的反应。

3.写一个显示播放电影信息的程序

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>写一个显示电影播放信息的程序</title>
    <script>
        function getTimeFromString(timeString) {
            var theTime = new Date();
            var time = timeString.match(/(\d+)(?::(\d\d))?\s*(p?)/);
            theTime.setHours(parseInt(time[1]) + (time[3] ? 12 : 00));
            theTime.setMinutes(parseInt(time[2]) || 0);
            return theTime.getTime();
        }
        function movie(title, genre, rating, showtimes) {
            this.title = title;
            this.genre = genre;
            this.rating = rating;
            this.showtimes = showtimes
            this.getNextShowing = function () {
                var now = new Date().getTime();
                for (var i = 0; i < this.showtimes.length; i++) {
                    var showtime = getTimeFromString(this.showtimes[i]);
                    if ((showtime - now) > 0) {
                        return "Next showing of" + " " + this.title + " " + 'is' + " " + this.showtimes[i] + " 电影类型是:" + this.genre + " 电影评级:" + this.rating;
                    }
                }
            };
        }
        var banzaimovie = new movie("你好,李焕英", "喜剧", "5", ["1:00pm", "5:00pm", "11:00pm"]);
        var plan9movie = new movie("唐人街判案4", "冒险", "5", ["3:00pm", "7:00pm", "11:00pm"]);
        var forbiddenPlaneMovie = new movie("大圣归来", "喜剧", "5", ["5:00pm", "9:00pm"]);
        alert(banzaimovie.getNextShowing());
        alert(plan9movie.getNextShowing());
        alert(forbiddenPlaneMovie.getNextShowing());

    </script>
</head>

<body>

</body>

</html>

函数和对象回顾

函数与对象回顾.png

4.地理位置API

HTML

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>地理位置API</title>
    <script src="myLoc2.js"></script>
    <link rel="stylesheet" href="myLoc.css">
</head>

<body>
    <div id="location">
        Your location will go here.
    </div>
    <div>
        Distance from WickedlySmart HQ will go here.
    </div>
    <div id="map">

    </div>
</body>

</html>


JS


window.onload = getMyLocation;//一旦浏览器加载页面,就调用这个函数
function getMyLocation() {
    if (navigator.geolocation) {//利用这个检查来确保浏览器支持地理定位API。如果navigator.geolocation(导航(拿哇给特),位置(节肉给神))对象存在,说明浏览器支持这个API。
        navigator.geolocation.getCurrentPosition(displayLocation);//如果浏览器支持地理定位API,则调用getCurrentPosition方法
        //并传入一个处理函数displaylocation,稍后就会实现这个函数,    displaylocation函数就是将要操纵的位置的处理程序。
    } else {
        alert("Oops,no geolocation support");//哎呀,不支持定位
    }
}

function displayLocation(position) {//displaylocation函数就是将要操纵的位置的处理程序。
    var latitude = position.coords.latitude;//position.coords(位置。坐标)对象得到位置的纬度
    var longitude = position.coords.longittude;//position.coords(位置。坐标)对象得到位置的和经度
    var div = document.getElementById('location');//从HTML中获取div
    div.innerHTML = "You are at Latitude:" + latitude + ",longitude:" + longittude;//使用innerHTML将Location<div>的内容设置为你的位置。


    var km = computeDistance(position.coords, ourCoords);
    var distance = document.getElementById("distance");
    distance.innerHTML = "you are" + km + "km from the wickedlySmart HQ"//这里将你的位置坐标以及我们的坐标传递到computeDistance.

    showMap(position.coords);//更新页面上的其他<div>之后,从displayLocation调用
}
var ourCoords = {
    latitude: 47.624851,
    longitude: -122.52099
};//作者位置


navigator.geolocation.getCurrentPosition(displayLocation, displayError);//为getcurentposition调用增加第二个函数,名为displayError,这是地理定位未能找到位置时要调用的一个函数。
function displayError(error) {//新处理程序,地理定位API会向它传入一个错误
    var errorTypes = {//error对象有一个code属性,其中包含一个0-3的数,这个是javascript为各个错误并联一个错误的好办法。
        0: "Unknown error",//这时"全包型"错误,如果其他错误都不合适就会使用这个错误,查看ERROR。message属性来了解更多信息
        1: "permission denied by user",//这个表示用户拒绝了使用位置信息的请求。
        2: "position is not available",//这说明浏览器尝试过,但是没有找到你的位置,同样的,查看error.message来得到更多的信息。
        3: "Request timed out"//地理定位有一个内部超时设置,如果超出了这个时限但没能确定位置,就会导致这个错误。
    };
    var errorMessage = errorTypes[error.code];//使用error.code属性,将一个错误消息串赋给一个新变量errormessage
    if (error.dode == 0 || error.code == 2) {
        errorMessage = errorMessage + " " + error.message;//对于错误0和2,有时error.message属性中会有一些额外的信息,所以把这些信息增加到errorMessage串。
    }
    var div = document.getElementById("location");//然后把这个消息增加到页面,让用户知道。
    div.innerHTML = errorMessage;


    function computeDistance(starCoords, destCoords) {
        var startLatRads = degreesToRadians(startCoords.latitude);
        var startLatRads = degreesToRadians(startCoords.longitude);
        var destCoords = degreesToRadians(startCoords.latitude);
        var destCoords = degreesToRadians(startCoords.longitude);

        var radius = 6371;//radius of the Earth in km
        var distance = Math.asos(Math.sin(startLatrads)) * Math.sin(destLatRads) +
            Math.cos(startLatrads) * Math.cos(destLatRads) *
            Math.cos(startLongRads - destLongrads) * radius;


        return distance;
    }

    function degreesToRadians(degrees) {
        var radians = (degress * Math.PI) / 180;
        return radians

    }
}//半正矢公式。使用这个代码就能知道两个坐标之间的距离


// 2.显示地图
var map; //我们声明了一个全局变量map,它包含我们将创建google地图
function showMap(coords) {
    var googleLatAndLong = new google.maps.LatLng(coords.latitude, coords.longitude);//使用coords(坐标)对象的latitude(纬度)和longitude(经度)。
    var mapOptions = {//用我们希望的地图选项建mapOption对象
        zoom: 10,
        center: googleLatAndLong,
        mapTypeId: google.maps.mapTypeId.ROADMAP

    };
    var mapDiv = document.getElementById("map");
    map = new google.maps.map(mapDiv, mapOptions);//将这个新的map对象赋给全局变量map
    //最后从DOM获取<div>,把它和mapOptions传递到map构造函数,创建google.maps.map对象。这会在我们页面上显示地图。

    var title = "Your Location";
    var conten = "you are here:" + coords.latitude + "," + coords.longittude;
    addMarker(map, googleLatAndLong, title, content);

}

//3.加一个大头钉
function addMarker(map, latlong, title, content) {
    var markerOptions = {
        position: latlong,
        map: mao,
        title: title,
        clickable: true
    };
    var marker = new google.maps.marker(markerOptions);

    var inforWindowOptions = {
        content: content,
        position: latlong
    };
    var infoWindow = new google.maps.InfoWindow(iforWindowOptions);
    google.maps.event.addListener(marker, "click", function () {
        infoWindow.open(map);
    })
}

5.写一个监控口香糖销售记录的程序

HTML

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <script src="mightygumball.js"></script>
    <link rel="stylesheet" href="mightygumball.css">
</head>

<body>
    <h1>Minghty Gumball Sales</h1>
    <div id="sales">
    </div>
</body>


</html>

JS

// window.onload = function () {
//     var url = "./data.json";//告诉浏览器到哪里找到我们想要的数据    1.建立一个服务器URL   
//     var request = new XMLHttpRequest();//                                               2.创建一个请求对象
//     request.open("GET", url);//url类型,HTTP请求类型                                     3.给它们两个指定类型
//     request.onload = function () {//获取数据之后,处理程序                              // 4.建立本地测试程序
//         if (request.status === 200) {//request请求,status状态
//             updateSales(request.responseText);//可以从requset对象的responseText属性得到响应    
//         }
//     };
//     request.send(null);//send发送
// }



//这个一个销售数据,返回给用户查看的程序
// function updateSales(responseText) {//update更新
//     var salesDiv = document.getElementById("sales");//sales销售        1.获取数据
//     var sales = JSON.parse(responseText);//parse解析 response响应      2.解析数据
//     console.log(sales);
//     for (var i = 0; i < sales.length; i++) {//迭代处理数组中的每一项   3.处理数据
//         var sale = sales[i];
//         var div = document.createElement("div");                        //4.创建数据存储位置
//         div.setAttribute("class", "saleItem");//setAttribute指定标签属性   5.指定数据存储位置的类型
//         div.innerHTML = sale.name + " &nbsp;sold" + sale.sales + "gumballs";//语义为:销售名+'有效的'+销售额+口香糖   //6.输出结果给用户
//         document.body.appendChild(div)
//     }
// };

//老版本浏览器不支持XMLHttpRequest onload属性,有一个简单的方法
// 使用XMLHttpRequestLevel 1的大多数代码都是一个样的
// function init() {
//     var url = "./data.json";
//     var request = new XHLHttpRequest();
//     request.onreadystatechange = function () {
//         if (request.readyState === 4 && request.status === 200) {//readystate状态值
//             updateSales(request.responseText);
//         }
//     };
//     request.open("GET", url);
//     request.send(null);
// }



//jsonp的的使用
var lastReporime = 0;
function updateSales(sales) {//输出结果给用户看的一个程序
    var salesDiv = document.getElementById("sales");
    for (var i = 0; i < sales.length; i++) {
        var sale = sales[i];
        var div = document.createElement("div");
        div.setAttribute("class", "saleItem")//.setAttribute()设置属性
        div.innerHTML = sale.name + " &nbsp;sold" + sale.sales + " gumballs "+" time&nbsp;&nbsp;"+sale.time;
        salesDiv.appendChild(div);
    }
    if (sales.length > 0) {
        lastReportime = sales[sales.length - 1].time;
    }
}


function handleRefresh() {//handleRefresh,处理刷新 ,获取数据的一个程序
    setInterval(handleRefresh, 3000)//定时器(函数,时间间隔)
    var url = "./mightygumballdate.js";//url地址
    const newScriptElement = document.createElement("script");
    newScriptElement.setAttribute("src", url);
    newScriptElement.setAttribute("id", "jsonp");

    const oldScriptElement = document.getElementById("jsonp");
    const head = document.getElementsByTagName("head")[0];//getElementBytagName方法返回得到head元素数组第一个元素
    if (oldScriptElement === null) {
        head.appendChild(newScriptElement);//添加子级元素
    }
    else {
        head.replaceChild(newScriptElement, oldScriptElement);//替换子级(新子级,老子级)
    }
}
handleRefresh()


JSonp


var data = [
    {
        "name": "a",
        "time": 1308774240669,
        "sales": 8
    },
    {
        "name": "b",
        "time": 1308774240670,
        "sales": 20
    },
    {
        "name": "b",
        "time": 13008774240671,
        "sales": 2
    },
    {
        "name": "b",
        "time": 13008774240671,
        "sales": 5
    },
    {
        "name": "d",
        "time": 13008774240672,
        "sales": 6
    },
    {
        "name": "f",
        "time": 13008774240672,
        "sales": 5
    }
]

updateSales(data)