【沿路行走】-javascript API

Fetch()

fetch();//从服务器或本地获取资源

then();处理fetch到的promise然后处理,处理完后返回promise,可以不断链式处理。

fetch('products.json').then(function(response) {
  if(response.ok) {
    response.json().then(function(json) {
      products = json;
      initialize();
    });
  } else {
    console.log('Network request for products.json failed with response ' + response.status + ': ' + response.statusText);
  }
});

catch(error)抓取获取资源过程中的错误返回。

关键字async  await

async function catchRainbow(){
    const response = await fetch("rainbow.jpg");
    const blob = await response.blob();
    document.getElementById("rainbow").src = URL.createObjectURL(blob);

} //返回依然是promise,只不过不用一直thenthen处理了,使用async await;
catchRainbow()
.then(response => {
    console.log("hhh");
})
.catch(error => {
    console.log("error!");
    console.error(error);
})

 绘制图表:chart.js 

地图:leaflet.js

p.js

node.js

可以让我们不依赖于浏览器,运行javascript

在命令行敲node即可进入javascript运行环境

node **.js //运行javascript文件中的代码

npm:node package manager管理node的所有包

我们可以导入node提供的某些功能包,然后使用它们实现某些功能

npm init //创建project package.json

npm install express(包名) 

然后就可以在js程序中使用包:

const express = require("express");
const app = express();
app.listen(3000,() => console.log(listen port 3000));
app.use(express.static("public"));//public中的html会被访问3000端口的客户端获取

Geolocation API 

获取经纬度等

 

处理事件

鼠标移动,点击按钮,缩放窗口等都成为称为事件,浏览器会监控这些事件,然后将这些事件传给javascript,javascript会根据事件类型,执行之前注册在该事件上的响应函数。

添加事件监听器:

监听整个html

<script>

        addEventListener('click',function(evt){

                document.body.innerHTML += 'button clicked!';

        });

</script>

监听特定DOM元素

  <button id="myButton">Click me!</button>
  <p></p>
  <script>
    var b = document.querySelector("#myButton");
    b.addEventListener('click', function(evt) {
      alert("Button clicked");
    });
  </script> 

 也可以使用on***内嵌在在标签内:

 <script>
         function processClick(evt) {
          alert("Button clicked");
        };
  </script> 
</head>
<body>
  <button id="myButton" onclick="processClick(event);">Click me!</button>
</body>

移除之前的监听,这样当再有相同事件发生时,不会有任何响应发生:

b.removeEventListener('click', processClick);

事件对象

 evt:事件对象

evt.type 事件名称

evt.target 事件作用的元素

和页面生命周期相关的事件对象

load 对象加载完成事件

集中添加事件方式:

<body onload="init();">

In a JS code, add window.onload = init;

in a JS code, add window.addEventListener('load', init);

resize 文档大小变化

scroll 滚动条滚动事件

window.onload = init;

var progressBar;

function init() {
  progressBar = document.querySelector(".progress div");

  window.addEventListener("scroll", function() {
      var max = document.body.scrollHeight - window.innerHeight;
      var percent = (window.pageYOffset / max) * 100;
      progressBar.style.width = percent + "%";
  });
}

 键盘事件

keydown: 按下键盘按键

keyup:释放键盘按键

keypress;按下和释放按键//被取消

按键事件的属性:

evt.key 得到按下的按键字符

evt.code 得到物理按键的编码

鼠标事件

click 点击事件

dbclick 双击

mousedown 按下鼠标按键

mouseup 释放鼠标按键

mousemove 移动鼠标

mouseenter 鼠标移动到元素上

mouseleave 鼠标移出元素

mouseover 鼠标移到元素或元素的子元素上

contextmenu 右击元素打开菜单

 鼠标事件对应的属性:

 表单和输入域的事件

 DOM API

可以被javascript掉用来控制html的内容和样式

太多,太复杂。。。

selector API

querySelector(selector) 返回匹配selector的第一个DOM元素

querySelectorAll(selector)返回满足selector的所有元素

function init() {
  // we're sure that the DOM is ready
  // before querying it
  
  // add a shadow to all images
  // select all images
  var listImages = document.querySelectorAll("img");

  // change all their width to 100px
  listImages.forEach(function(img) {
    // img = current image
    img.style.boxShadow = "5px 5px 15px 5px grey";
    img.style.margin = "10px";
  });  
  
}

function addBorderToFirstImage() {
  // select the first image with id = img1
  var img1 = document.querySelector('#img1');

  // Add a red border, 3px wide
  img1.style.border = '3px solid red';  
}

改变CSS属性

element.style.cssAttribute;

  1. // select the paragraph with id = "paragraph1"
  2. var p = document.querySelector('#paragraph1');
  3. // change its color
  4. p.style.color = 'red';

 修改选中元素的文本内容

innerHTML 原封不动显示选择的标签中的内容,包括其他标签<>

  1. var elem = document.querySelector('#myElem');
  2. elem.innerHTML = 'Hello '; // replace content by Hello

textContent 只显示选择标签及子标签的文本值

创建新元素

 createElement(name_of_the_element);

  1. var li = document.createElement('li');

 设置新元素的属性

  1. li.innerHTML = '<b>This is a new list item in bold!</b>'; // can add HTML in it
  2. li.textContent = 'Another new list item';
  3. li.style.color = 'green'; // green text

 在指定元素周围添加新元素

  1. var ul = document.querySelector('#myList');
  2. ul.append(li); // insert at the end, appendChild() could also be used (old)
  3. ul.prepend(li); // insert at the beginning
  4. ul.insertBefore(li, another_element_child_of_ul);// insert in the middle
  5. document.body.append(img); // adds the image at the end of the document

 移动元素

function move(elem) {
  var targetList = document.querySelector('#coolBrowsers');
  targetList.append(elem);
  
  // trick to remove the click listener once
  // the image has been moved into the list
  elem.onclick = null;
}
 <img src="https://mainline.i3s.unice.fr/mooc//ABiBCwZ.png" id="cr" 
       onclick="move(this)" alt="Logo Chrome">
  <img 

移除元素

removeChild()

迭代器

arr.forEach(function(parameters){}) 将arr中的每个元素作为参数传给function

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值