前端雜的學習筆記

什么是nginx

Nginx (engine x) 是一個高性能的HTTP和反向代理web服務器

Nginx是一款輕量級的Web 服務器/反向代理服務器,處理高并發能力是十分強大的,并且支持熱部署,啟動簡單,可以做到7*24不間斷運行

正代和反代

學習nginx,最重要的就是反向代理

img

img

安裝nginx

直接安裝

初學者可以嘗試這種模式

yum install -y nginx

docker安裝

docker pull nginx:latest
?
docker run -itd --name nginx -p 80:80 nginx:latest

用docker的話,就把配置文件和目錄映射出來,方便修改

常用命令

# 開啟服務
nginx
# 快速停止
nginx -s stop
# 有序停止
nginx -s quit
# 重啟服務:
nginx -s reload
# 檢查配置文件是否有語法操作
nginx -t

nginx.conf

nginx默認配置文件

一般在/usr/local/nginx/conf/nginx.conf

nginx.conf由多個塊組成,最外面的塊是main,main包含Events和HTTP,HTTP包含upstream和多個Server,Server又包含多個location

user  nginx; ?# 指定nginx進程的運行用戶
worker_processes  auto; # 指定Nginx要開啟的進程數,每個Nginx進程平均耗費10M~12M內存。建議指定和CPU的數量一致即可。
?
error_log  /var/log/nginx/error.log notice; # 用來定義全局錯誤日志文件。日志輸出級別有debug、info、notice、warn、error、crit可供選擇,其中,debug輸出日志最為最詳細,而crit輸出日志最少。
pid ? ? ?  /var/run/nginx.pid; # 用來指定進程pid的存儲文件位置
?
?
events {worker_connections  1024; ?# 用于定義Nginx每個進程的最大連接數,默認是1024
}
?
?
http {include ? ? ? /etc/nginx/mime.types;default_type  application/octet-stream; ? # 這里設定默認類型為二進制流,也就是當文件類型未定義時使用這種方式,例如在沒有配置PHP環境時,Nginx是不予解析的,此時,用瀏覽器訪問PHP文件就會出現下載窗口。
?log_format ?main ?'$remote_addr - $remote_user [$time_local] "$request" ''$status $body_bytes_sent "$http_referer" ''"$http_user_agent" "$http_x_forwarded_for"';
?access_log  /var/log/nginx/access.log  main;
?sendfile ? ? ?  on; # 用于開啟高效文件傳輸模式。將tcp_nopush和tcp_nodelay兩個指令設置為on用于防止網絡阻塞;
?keepalive_timeout  65; ?# 設置客戶端連接保持活動的超時時間。在超過這個時間之后,服務器會關閉該連接;
?
?include /etc/nginx/conf.d/*.conf;  # 導入其他的配置文件,注意include所在的位置
}

main(全局設置)、server(主機設置)、upstream(負載均衡服務器設置)和 location(URL匹配特定位置的設置)。

  • main塊設置的指令將影響其他所有設置;

  • server塊的指令主要用于指定主機和端口;

  • upstream指令主要用于負載均衡,設置一系列的后端服務器;

  • location塊用于匹配網頁位置。

localtion

URL地址匹配是進行Nginx配置中最靈活的部分。 location支持正則表達式匹配,也支持條件判斷匹配,用戶可以通過location指令實現Nginx對動、靜態網頁進行過濾處理

img

我這里準備了一個html文件,html文件引入了圖片

然后配置文件如下:

server {listen 80;location / {root /opt/nginx_study/html; # 根目錄index index.html; # 默認顯示的頁面}
}

此時訪問服務器ip就可以正常看到頁面和圖片

注意啊,在html引入圖片是相對路徑,如果你這樣寫

<img src="/html/image/1.jpg" alt="">
<img src="/html/image/2.jpg" alt="">

不改nginx的情況下,頁面上能看到圖片嗎?

答案是肯定的,肯定看不到的

那我們可以配置一下圖片的訪問路徑

server {listen 80;
?location ~ .*\.(gif|jpg|jpeg|png|bmp|swf)$ {root /opt/nginx_study;}location / {root /opt/nginx_study/html; # 根目錄index index.html; # 默認顯示的頁面}
}

或者

server {listen 80;
?location /html/ { # 后面沒有/就會重定向root /opt/nginx_study;index image/1.jpg; ?# 直接訪問這個路徑,會顯示這個圖片}location / {root /opt/nginx_study/html; # 根目錄index index.html; # 默認顯示的頁面}
?
?
}

alias

Nginx中配置文件路徑有兩種方式,一種是root一種是alias

例如一個項目里面,有兩個html文件要配置路由去訪問

目錄如下

htmlhtml1index.htmlhtml2index.html

我想實現 訪問127.0.0.1:80就是 訪問html1下的index.html

訪問127.0.0.1:80/xxx就是 訪問html2下的index.html

如果這樣寫,會發現/xxx/怎么也到不了/html2那里

server {listen 80;location / {root /opt/nginx_study/html/html1;index index.html;}location /xxx/ {root /opt/nginx_study/html/html2/;  # 會把/xxx/的路徑拼接上index index.html;}
}

所以就有了路徑別名

這樣就可以解決這個問題了

server {listen 80;location / {root /opt/nginx_study/html/html1;index index.html;}location /xxx/ {alias /opt/nginx_study/html/html2/;  # 只會把/xxx/后面的路徑拼接過來index index.html;}
}

域名配置

server_name

如果你的項目是用ip訪問的話,這個可以不寫

但是如果你的服務器上要跑很多服務,并且都想使用80端口去訪問

那就使用域名

通過訪問不同的子域名來訪問不同的服務

準備三個目錄,方便讓三個子域名訪問

img

因為演示是在內網環境,沒有真正的域名可以用

所以我們只能修改訪問者的hosts文件,將上面三個域名執行到 目標服務器上

例如我現在的hosts文件

192.168.100.185 doc.fengfengzhidao.com
192.168.100.185 news.fengfengzhidao.com
192.168.100.185 video.fengfengzhidao.com

然后配置nginx配置文件

server {listen 80;server_name doc.fengfengzhidao.com;location / {root /opt/nginx_study/html/doc.fengfengzhidao.com;index index.html;}
}
server {listen 80;server_name news.fengfengzhidao.com;location / {root /opt/nginx_study/html/news.fengfengzhidao.com;index index.html;}
}
server {listen 80;server_name video.fengfengzhidao.com;location / {root /opt/nginx_study/html/video.fengfengzhidao.com;index index.html;}
}

測試

C:\Users\楓楓>curl http://doc.fengfengzhidao.com
<!DOCTYPE html>
<html lang="en">
<head><meta charset="UTF-8"><title>Title</title>
</head>
<body>
doc.fengfengzhidao.com
</body>
</html>C:\Users\楓楓>curl http://news.fengfengzhidao.com
<!DOCTYPE html>
<html lang="en">
<head><meta charset="UTF-8"><title>Title</title>
</head>
<body>
news.fengfengzhidao.com
</body>
</html>C:\Users\楓楓>curl http://video.fengfengzhidao.com
<!DOCTYPE html>
<html lang="en">
<head><meta charset="UTF-8"><title>Title</title>
</head>
<body>
video.fengfengzhidao.com
</body>
</html>
其他匹配模式

server_name 中支持通配符 "*", 但需要注意的是通配符不能出現在域名的中間,只能出現在首段或尾段

server_name 中可以使用正則表達式,并且使用 ~ 作為正則表達式字符串的開始標記

有些博客網站,用戶創建博客之后就會得到一個自己的專屬博客,我們可以使用通配符來實現這個修改

server {listen 80;server_name *.bolg.fengfengzhidao.com;location / {root /opt/nginx_study/html/doc.fengfengzhidao.com;index index.html;}
}

也可以使用正則表達式

這樣就只能 zhangsan lisi wangwu三個訪問

server {listen 80;server_name ~^(zhangsan)|(lisi)|(wangwu).bolg.fengfengzhidao.com$;location / {root /opt/nginx_study/html/doc.fengfengzhidao.com;index index.html;}
}

當然,前端肯定要獲取當前的子域名是什么,然后發給后端查詢是否有這個用戶

我們的hosts文件

192.168.100.185 blog.fengfengzhidao.com
192.168.100.185 zhangsan.blog.fengfengzhidao.com
192.168.100.185 lisi.blog.fengfengzhidao.com
192.168.100.185 wangwu.blog.fengfengzhidao.com
192.168.100.185 fengfeng.blog.fengfengzhidao.com

認證

img

經常能看到這種輸入用戶名密碼才能訪問的網頁

這種效果是怎么實現的呢

使用htpasswd生成特定的密碼文件

yum install httpd-tools -y

這里我以test用戶,密碼123456為例

htpasswd -c  /opt/nginx_study/auth/htpasswd  test

img

nginx配置認證

server {listen 80;location / {# 開啟功能模塊,關閉為offauth_basic on;# 指定密碼配置文件auth_basic_user_file /opt/nginx_study/auth/htpasswd;root /opt/nginx_study/html; # 根目錄index index.html; # 默認顯示的頁面}}

如果是用curl訪問

curl -u test:123456 http://127.0.0.1

proxy_pass

這個就是nginx的重頭戲了,nginx的代理

一般是針對特定的路由,代理到后端服務器上

例如我這里寫了一個程序,匹配全部的路徑,然后打印出來

package mainimport ("encoding/json""flag""fmt""github.com/gin-gonic/gin"
)var name *string// handler
func handler(c *gin.Context) {byteData, _ := json.Marshal(c.Request.Header)fmt.Println(string(byteData))c.String(200, fmt.Sprintf("%s %s name:%s", c.Request.URL.Path, c.ClientIP(), *name))return
}func main() {addr := flag.String("addr", ":8080", "addr")name = flag.String("name", "default", "name")flag.Parse()router := gin.Default()router.GET("", handler)fmt.Println("服務運行中...")fmt.Printf("服務運行在:%s \n", *addr)router.Run(*addr)
}

build.bat

set GOOS=linux
go build -o main
set GOOS=windows

然后將編譯好的文件,放在服務器上運行

然后配置proxy_pass

server {listen 80;location /a1/ {  # 匹配/a1/開始,將/a1/之后的加到/之后proxy_pass http://127.0.0.1:8080/;}location /a2/ {   # 匹配/a2/開始,將匹配的路徑加到/之后,直觀感受就是把被匹配的路徑加上了proxy_pass http://127.0.0.1:8080;}location /b1/ {proxy_pass http://127.0.0.1:8080/xxx/;}location /b2/ {proxy_pass http://127.0.0.1:8080/xxx;}
}

這里這個路徑會有絕對路徑和相對路徑的說法,演示一下就清楚了

請求路徑                              實際到后端的路徑
/a1/                                     /
/a1/123                                  /123/a2/                                     /a2/
/a2/123                                  /a2/123/b1/                                     /xxx/
/b1/123                                  /xxx/123/b2/                                     /xxx
/b2/123                                  /xxx123
攜帶原始ip

這個時候,你會發現,我請求192.168.100.185這個服務器ip

但是在服務內部接收到的ip全是127.0.0.1,這是為什么呢

我們都知道,nginx的proxy就是代理,將源用戶的請求代理到目標服務器上,也就是請求者變成了nginx

我們只需要將源請求的標識ip的特征,一起代理過去就行

主要配置一個特殊的請求頭就可以了

server {listen 80;# proxy_set_header X-Real-IP $remote_addr; # 加在這里也可以location /a1/ {proxy_set_header X-Real-IP $remote_addr;proxy_pass http://127.0.0.1:8080/;}
}

負載均衡

nginx應用場景之一就是負載均衡。在訪問量較多的時候,可以通過負載均衡,將多個請求分攤到多臺服務器上,相當于把一臺服務器需要承擔的負載量交給多臺服務器處理,進而提高系統的吞吐率;另外如果其中某一臺服務器掛掉,其他服務器還可以正常提供服務,以此來提高系統的可伸縮性與可靠性。

后端啟動兩個服務

./main -addr 127.0.0.1:8080 -name s1
./main -addr 127.0.0.1:8081 -name s2
upstream myapp1 {server 127.0.0.1:8080;server 127.0.0.1:8081;
}server {listen 80;location /api/ {proxy_set_header X-Real-IP $remote_addr;proxy_pass http://myapp1/;}
}

然后訪問 服務器ip:80/api/

你會發現分別將請求打到不同的后端服務上了

此時它們的權重是一樣的

nginx給我們提供了不同的權重模式

輪詢(Nginx自帶、默認)

該策略是Nginx默認的負載均衡策略,每一個客戶端請求按時間順序輪流分配到不同的服務器上,如果后端服務不可以用,會自動過濾掉。

weight 權重(Nginx自帶)

upstream myapp1 {server 127.0.0.1:8080 weight=1;  # 打中的比例是 1/3server 127.0.0.1:8081 weight=2;  # 打中的比例是 2/3
}

ip_hash(Nginx自帶)

ip_hash是將每個請求按照訪問ip的hash結果進行分配,這種方式可以保證同一個用戶會固定訪問一個后端服務器。優點:可以保證session會話,解決服務器之間session不能共享的問題。

upstream myapp1 {ip_hash;server 127.0.0.1:8080;server 127.0.0.1:8081;
}server {listen 80;location /api/ {proxy_set_header X-Real-IP $remote_addr;proxy_pass http://myapp1/;}
}

least_conn(Nginx自帶)

將請求轉發給連接數較少的后端服務器。每個后端服務器配置可能不同,處理的請求也有可能不同,對于處理的請求有快有慢,least_conn是根據后端服務器的連接情況,動態的選擇連接數量較少的一臺服務器來處理當前的請求。

upstream myapp1 {least_conn;server 127.0.0.1:8080;server 127.0.0.1:8081;
}server {listen 80;location /api/ {proxy_set_header X-Real-IP $remote_addr;proxy_pass http://myapp1/;}
}

nginx限制措施

黑名單

nginx的黑名單功能可以直接在nginx層面攔截惡意ip,讓它到不了后端服務

被攔截之后的效果就是這樣

img

它的配置也很簡單

server {listen 80;
#     deny 192.168.100.113;  # 可以放在 server塊location / {root /opt/nginx_study/html/;index index.html;}location /yyy/ {deny 192.168.100.113; # 也可以放在location塊中alias /opt/nginx_study/html/;index index.html;}
}

deny 這個配置也是不挑地方的,可以放在不同的作用域中

也可以專門用一個文件去存放黑名單,只需要在不同的地方include即可,如下

black.conf

deny 192.168.100.113;

nginx.conf

server {listen 80;location / {root /opt/nginx_study/html/;index index.html;}include /opt/nginx_study/black.conf;
}

白名單

allow,一般和deny 連用

如下,只允許192.168.100.113訪問,其他ip訪問則被拒絕

server {listen 80;allow 192.168.100.113;deny all;location / {root /opt/nginx_study/html/;index index.html;}
}

UA黑名單

map $http_user_agent $bad_user_agent {default         0;~*curl           1;~*wget           1;~*Unicornscan    1;~*sqlmap         1;~*nessus         1;~*netsparker     1;}server {listen 80;if ($bad_user_agent) {return 404;}location / {root /opt/nginx_study/html/;index index.html;}
}

注意,這個map只能寫在server的外面

此時,通過 curl直接訪問會得到 404

C:\Users\楓楓>curl 192.168.100.185
<html>
<head><title>404 Not Found</title></head>
<body bgcolor="white">
<center><h1>404 Not Found</h1></center>
<hr><center>nginx/1.13.7</center>
</body>
</html>C:\Users\楓楓>curl --user-agent sss 192.168.100.185
<!DOCTYPE html>
<html lang="en">
<head><meta charset="UTF-8"><title>Title</title>
</head>
<body>
你會
</body>
</html>

Referer黑名單

map $http_referer $bad_referer {default         0;~*evil\.com     1;~*xxx\.com      1;~*yyy\.com      1;}server {listen 80;if ($bad_referer) {return 404;}location / {root /opt/nginx_study/html/;index index.html;}
}
C:\Users\楓楓>curl 192.168.100.185
<!DOCTYPE html>
<html lang="en">
<head><meta charset="UTF-8"><title>Title</title>
</head>
<body>
你會
</body>
</html>C:\Users\楓楓>curl -e xxx.com 192.168.100.185
<html>
<head><title>404 Not Found</title></head>
<body bgcolor="white">
<center><h1>404 Not Found</h1></center>
<hr><center>nginx/1.13.7</center>
</body>
</html>

請求頻率黑名單

黑客可以通過發送大量請求來模擬各種攻擊,在一定時間內發送的請求達到某個閾值后則會被判定為惡意請求。實現請求頻率限制也是黑名單的一種應用場景

這是一分鐘內請求5次的示例

limit_req_zone $binary_remote_addr zone=perip:10m rate=5r/m;server {listen 80;limit_req zone=perip burst=5 nodelay;location / {root /opt/nginx_study/html/;index index.html;}
}

這是一秒鐘內請求5次的示例

limit_req_zone $binary_remote_addr zone=perip:10m rate=5r/s;server {listen 80;limit_req zone=perip burst=10 nodelay;  # 最多可以處理10個并發請求location / {root /opt/nginx_study/html/;index index.html;}
}

https配置

自簽名ssl證書
openssl genrsa -out private.key 2048
openssl req -new -key private.key  -out cert.csr
openssl x509 -req -in cert.csr -out cacert.pem -signkey private.key
server {listen 443 ssl;ssl_certificate /opt/nginx_study/ssl/cacert.pem;  # pem的路徑ssl_certificate_key /opt/nginx_study/ssl/private.key;  # key的路徑location / {root /opt/nginx_study/html/;index index.html;}
}

因為是自簽的,所以瀏覽器會提示不安全,正常的

img

云平臺的ssl證書

將key和pem文件放到服務器上

server {listen 80;  # 將80的請求重定向到443上去server_name www.xxx.com;return 301 https://$server_name$request_uri; 
}server {listen 443 ssl;ssl_certificate /www/server/nginx/www.xxx.com.pem;  # pem的路徑ssl_certificate_key /www/server/nginx/www.xxx.com.key;  # key的路徑server_name www.xxx.com;location / {uwsgi_pass   127.0.0.1:8000;  # 這個案例是uwsgi的案例include uwsgi_params;}location /static {alias  /www/wwwroot/flask_deploy/static;}
}

gzip配置

這個配置也是不挑地方的

server {listen 80;location / {gzip on;gzip_types text/plain text/css application/json application/javascript text/xml application/xml application/xml+rss text/javascript;root /opt/nginx_study/html/;index index.html;}location /xxx/ {alias /opt/nginx_study/html/;index index.html;}
}

img

img

參考文檔

官網:nginx

nginx詳解:Nginx詳解(一文帶你搞懂Nginx)-CSDN博客

nginx常用命令操作:nginx常用操作命令_nginx命令-CSDN博客

8分鐘了解nginx:https://zhuanlan.zhihu.com/p/34943332

nginx常用命令和總結:nginx的常用命令和總結 - ministep88 - 博客園

nginx配置文件: Nginx安裝及配置文件nginx.conf詳解-CSDN博客

nginx負載均衡:百度安全驗證

nginx server_name: nginx 配置指令之server_name_nginx servername-CSDN博客

nginx 黑名單: 如何使用Nginx實現IP黑名單-Nginx-PHP中文網

nginx請求頻率限制:https://www.python100.com/html/109613.html

nginx gzip: Nginx中啟用Gzip壓縮加速網頁加載,-CSDN博客

nginx gzip具體配置: Nginx Gzip配置詳解:優化壓縮效率與范圍-CSDN博客

jQuery 安裝

下載 jQuery

有兩個版本的 jQuery 可供下載:

  • Production version - 用于實際的網站中,已被精簡和壓縮

  • Development version - 用于測試和開發(未壓縮,是可讀的代碼)

以上兩個版本都可以從 jquery.com 中下載

<head><script src="jquery-1.10.2.min.js"></script>
</head>

替代方案

Staticfile CDN:

<head><script src="https://cdn.staticfile.net/jquery/1.10.2/jquery.min.js"></script>
</head>

百度 CDN:

<head><script src="https://apps.bdimg.com/libs/jquery/2.1.4/jquery.min.js"></script>
</head>

字節跳動:

<head><script src="https://lf3-cdn-tos.bytecdntp.com/cdn/expire-1-M/jquery/2.1.3/jquery.min.js"></script>
</head>

又拍云 CDN:

<head><script src="https://upcdn.b0.upaiyun.com/libs/jquery/jquery-2.0.2.min.js"></script>
</head>

新浪 CDN:

<head><script src="https://lib.sinaapp.com/js/jquery/2.0.2/jquery-2.0.2.min.js"></script>
</head>

Microsoft CDN:

<head><script src="https://ajax.aspnetcdn.com/ajax/jquery/jquery-1.9.0.min.js"></script>
</head>

jQuery 語法

基礎語法: $(selector).action()

  • $(this).hide() - 隱藏當前元素

  • $("p").hide() - 隱藏所有 <p> 元素

  • $("p.test").hide() - 隱藏所有 class="test" 的 <p> 元素

  • $("#test").hide() - 隱藏 id="test" 的元素

文檔就緒事件

實例中的所有 jQuery 函數位于一個 document ready 函數中:

$(document).ready(function(){// 執行代碼
});
// 或者
$(function(){// 執行代碼
});

jQuery 選擇器

元素選擇器

<script src="https://cdn.staticfile.net/jquery/2.0.0/jquery.min.js">
</script>
<script>$(document).ready(function(){$("button").click(function(){$("p").hide();});});
</script>
</head>
<body><h2>這是一個標題</h2><p>這是一個段落</p><button>點我</button>
</body>

#id 選擇器

<script src="https://cdn.staticfile.net/jquery/1.10.2/jquery.min.js">
</script>
<script>$(document).ready(function(){$("button").click(function(){$("#test").hide();});});
</script>
</head>
<body><h2>這是一個標題</h2><p>這是一個段落</p><p id="test">這是另外一個段落</p><button>點我</button>
</body>

.class 選擇器

<script src="https://cdn.staticfile.net/jquery/1.10.2/jquery.min.js">
</script>
<script>$(document).ready(function(){$("button").click(function(){$(".test").hide();});});
</script>
</head>
<body><h2 class="test">這是一個標題</h2><p class="test">這是一個段落</p><p>這是另外一個段落</p><button>點我</button>
</body>

更多實例

語法描述
$("*")選取所有元素
$(this)選取當前 HTML 元素
$("p.intro")選取 class 為 intro 的 <p> 元素
$("p:first")選取第一個 <p> 元素
$("ul li:first")選取第一個 <ul> 元素的第一個 <li> 元素
$("ul li:first-child")選取每個 <ul> 元素的第一個 <li> 元素
$("[href]")選取帶有 href 屬性的元素
$("a[target='_blank']")選取所有 target 屬性值等于 "_blank" 的 <a> 元素
$("a[target!='_blank']")選取所有 target 屬性值不等于 "_blank" 的 <a> 元素
$(":button")選取所有 type="button" 的 <input> 元素 和 <button> 元素
$("tr:even")選取偶數位置的 <tr> 元素
$("tr:odd")選取奇數位置的 <tr> 元素

獨立文件中使用 jQuery 函數

<head><script src="http://cdn.static.runoob.com/libs/jquery/1.10.2/jquery.min.js"></script><script src="my_jquery_functions.js"></script>
</head>

jQuery 事件

鼠標事件鍵盤事件表單事件文檔/窗口事件
clickkeypresssubmitload
dblclick 雙擊元素時警報keydownchange 規定針對被選元素當 change 事件發生時運行的函數resize
mouseenterkeyupfocus 獲得焦點時發生 focus 事件scroll
mouseleaveblur 失去焦點時發生 blur 事件unload
hover

鼠標事件

<script src="https://cdn.staticfile.net/jquery/1.10.2/jquery.min.js">
</script>
<script>$(document).ready(function(){$("p").click(function(){$(this).fadeOut();});});
</script>
</head>
<body><p>點擊這個段落,使其消失。</p>
</body>
<script>$(document).ready(function(){$("p").dblclick(function(){$(this).fadeOut();});});
</script>
<script src="https://cdn.staticfile.net/jquery/1.10.2/jquery.min.js">
</script>
<script>$(document).ready(function(){$("p").mouseenter(function(){$("p").css("background-color","yellow");});$("p").mouseleave(function(){$("p").css("background-color","lightgray");});});
</script>
</head>
<body><p>鼠標移動到該段落。</p>
</body>
<script src="https://cdn.staticfile.net/jquery/1.10.2/jquery.min.js">
</script>
<script>$(document).ready(function(){$("p").hover(function(){$("p").css("background-color","yellow");},function(){$("p").css("background-color","pink");});});
</script>
</head>
<body><p>鼠標移動到該段落。</p>
</body>

鍵盤事件

與 keypress 事件相關的事件順序:

  1. keydown 鍵按下的過程

  2. keypress 鍵被按下

  3. keyup 鍵被松開

<script src="https://cdn.staticfile.net/jquery/1.10.2/jquery.min.js">
</script>
<script>i=0;$(document).ready(function(){$("input").keypress(function(){$("span").text(i+=1);});});
</script>
</head>
<body>輸入你的名字: <input type="text"><p>按鍵的次數: <span>0</span></p>
</body>
<script src="https://cdn.staticfile.net/jquery/1.10.2/jquery.min.js">
</script>
<script>$(document).ready(function(){$("input").keydown(function(event){ $("div").html("Key: " + event.which);});});
</script>
</head>
<body>輸入名稱: <input type="text"><p>當你在以上輸入框中輸入內容時,div 中會陷入輸入鍵的數字碼。</p><div />
</body>
<script src="https://cdn.staticfile.net/jquery/1.10.2/jquery.min.js">
</script>
<script>$(document).ready(function(){$("input").keydown(function(){$("input").css("background-color","yellow");});$("input").keyup(function(){$("input").css("background-color","pink");});});
</script>
</head>
<body>輸入你的名字: <input type="text"><p>在以上輸入框中輸入你的名字。在按鍵按下后輸入框背景顏色會改變。</p>
</body>

表單事件

當提交表單時,顯示警告框:

<script src="https://cdn.staticfile.net/jquery/1.10.2/jquery.min.js">
</script>
<script>$(document).ready(function(){$("form").submit(function(){alert("Submitted");});$("button").click(function(){$("form").submit();});  });
</script>
</head>
<body><form action="">First name: <input type="text" name="FirstName" value="Mickey"><br>Last name: <input type="text" name="LastName" value="Mouse"><br></form> <button>觸發 submit 事件</button>
</body>

文檔/窗口事件

$(document).ready(function(){$("img").load(function(){alert("圖片已載入");});
});

對瀏覽器窗口調整大小進行計數

<script>x=0;$(document).ready(function(){$(window).resize(function(){$("span").text(x+=1);});});
</script>

對元素滾動的次數進行計數

<script src="https://cdn.staticfile.net/jquery/1.10.2/jquery.min.js">
</script>
<script>x=0;$(document).ready(function(){$("div").scroll(function(){$("span").text(x+=1);});});
</script>
</head>
<body><p>嘗試滾動 div 中的滾動條</p><div style="border:1px solid black;width:200px;height:100px;overflow:scroll;">菜鳥教程 —— 學的不僅是技術,更是夢想!菜鳥教程 —— 學的不僅是技術,更是夢想!<br><br>菜鳥教程 —— 學的不僅是技術,更是夢想!菜鳥教程 —— 學的不僅是技術,更是夢想!</div><p>滾動了 <span>0</span> 次。</p>
</body>

當離開頁面時,顯示提示消息

$(window).unload(function(){alert("Goodbye!");
});

jQuery 效果- 隱藏和顯示

<script src="https://cdn.staticfile.net/jquery/1.10.2/jquery.min.js">
</script>
<script>$(document).ready(function(){$("#hide").click(function(){$("p").hide(1000);});$("#show").click(function(){$("p").show(1000);});});
</script>
</head>
<body><p>如果你點擊“隱藏” 按鈕,我將會消失。</p><button id="hide">隱藏</button><button id="show">顯示</button>
</body>
<script src="https://cdn.staticfile.net/jquery/1.10.2/jquery.min.js">
</script>
<style>div{width: 130px;height: 50px;padding: 15px;margin: 15px;background-color: green;}
</style>
<script>$(document).ready(function(){$(".hidebtn").click(function(){$("div").hide(1000,"linear",function(){alert("Hide() 方法已完成!");});});});
</script>
</head>
<body><div>隱藏及設置回調函數</div><button class="hidebtn">隱藏</button>
</body>
<script>$(document).ready(function(){$("button").click(function(){$("p").toggle(1000);});});
</script>

jQuery Callback 方法

許多 jQuery 函數涉及動畫。這些函數也許會將 speedduration 作為可選參數

speedduration 參數可以設置許多不同的值,比如 "slow", "fast", "normal" 或毫秒

<!-- 在隱藏效果完全實現后回調函數 -->
<script src="https://cdn.staticfile.net/jquery/1.10.2/jquery.min.js">
</script>
<script>$(document).ready(function(){$("button").click(function(){$("p").hide("slow",function(){alert("段落現在被隱藏了");});});});
</script>
</head>
<body><button>隱藏</button><p>我們段落內容,點擊“隱藏”按鈕我就會消失</p>
</body>
<!-- 沒有回調函數,警告框會在隱藏效果完成前彈出 -->
<script src="https://cdn.staticfile.net/jquery/1.10.2/jquery.min.js">
</script>
<script>$(document).ready(function(){$("button").click(function(){$("p").hide(1000);alert("現在段落被隱藏了");});});
</script>
</head>
<body><button>隱藏</button><p>這是一個段落,內容很少</p>
</body>

jQuery 效果 - 淡入淡出

jQuery fadeIn() 方法

jQuery fadeIn() 用于淡入已隱藏的元素

<script src="https://cdn.staticfile.net/jquery/1.10.2/jquery.min.js">
</script>
<script>$(document).ready(function(){$("button").click(function(){$("#div1").fadeIn();$("#div2").fadeIn("slow");$("#div3").fadeIn(3000);});});
</script>
</head>
<body><p>以下實例演示了 fadeIn() 使用了不同參數的效果。</p><button>點擊淡入 div 元素</button><br><br><div id="div1" style="width:80px;height:80px;display:none;background-color:red;"></div><br><div id="div2" style="width:80px;height:80px;display:none;background-color:green;"></div><br><div id="div3" style="width:80px;height:80px;display:none;background-color:blue;"></div>
</body>

jQuery fadeOut() 方法

jQuery fadeOut() 方法用于淡出可見元素

<script src="https://cdn.staticfile.net/jquery/1.10.2/jquery.min.js">
</script>
<script>$(document).ready(function(){$("button").click(function(){$("#div1").fadeOut();$("#div2").fadeOut("slow");$("#div3").fadeOut(3000);});});
</script>
</head>
<body><p>以下實例演示了 fadeOut() 使用了不同參數的效果。</p><button>點擊淡出 div 元素。</button><br><br><div id="div1" style="width:80px;height:80px;background-color:red;"></div><br><div id="div2" style="width:80px;height:80px;background-color:green;"></div><br><div id="div3" style="width:80px;height:80px;background-color:blue;"></div>
</body>

jQuery fadeToggle() 方法

jQuery fadeToggle() 方法可以在 fadeIn() 與 fadeOut() 方法之間進行切換

<script src="https://cdn.staticfile.net/jquery/1.10.2/jquery.min.js">
</script>
<script>$(document).ready(function(){$("button").click(function(){$("#div1").fadeToggle();$("#div2").fadeToggle("slow");$("#div3").fadeToggle(3000);});});
</script>
</head>
<body><p>實例演示了 fadeToggle() 使用了不同的 speed(速度) 參數。</p><button>點擊淡入/淡出</button><br><br><div id="div1" style="width:80px;height:80px;background-color:red;"></div><br><div id="div2" style="width:80px;height:80px;background-color:green;"></div><br><div id="div3" style="width:80px;height:80px;background-color:blue;"></div>
</body>

jQuery fadeTo() 方法

jQuery fadeTo() 方法允許漸變為給定的不透明度(值介于 0 與 1 之間)

<script src="https://cdn.staticfile.net/jquery/1.10.2/jquery.min.js">
</script>
<script>$(document).ready(function(){$("button").click(function(){$("#div1").fadeTo("slow",0.15);$("#div2").fadeTo("slow",0.4);$("#div3").fadeTo("slow",0.7);});});
</script>
</head>
<body><p>演示 fadeTo() 使用不同參數</p><button>點我讓顏色變淡</button><br><br><div id="div1" style="width:80px;height:80px;background-color:red;"></div><br><div id="div2" style="width:80px;height:80px;background-color:green;"></div><br><div id="div3" style="width:80px;height:80px;background-color:blue;"></div>
</body>

jQuery 效果 - 滑動

jQuery slideDown() 方法

jQuery slideDown() 方法用于向下滑動元素

<script src="https://cdn.staticfile.net/jquery/1.10.2/jquery.min.js">
</script>
<script> $(document).ready(function(){$("#flip").click(function(){$("#panel").slideDown("slow");});});
</script>
<style type="text/css"> #panel,#flip {padding:5px;text-align:center;background-color:#e5eecc;border:solid 1px #c3c3c3;}#panel {padding:50px;display:none;}
</style>
</head>
<body><div id="flip">點我滑下面板</div><div id="panel">Hello world!</div>
</body>

jQuery slideUp() 方法

jQuery slideUp() 方法用于向上滑動元素

<script src="https://cdn.staticfile.net/jquery/1.10.2/jquery.min.js">
</script>
<script> $(document).ready(function(){$("#flip").click(function(){$("#panel").slideUp("slow");});});
</script>
<style type="text/css"> #panel,#flip {padding:5px;text-align:center;background-color:#e5eecc;border:solid 1px #c3c3c3;}#panel {padding:50px;}
</style>
</head>
<body><div id="flip">點我拉起面板</div><div id="panel">Hello world!</div>
</body>

jQuery slideToggle() 方法

jQuery slideToggle() 方法可以在 slideDown() 與 slideUp() 方法之間進行切換

<script src="https://cdn.staticfile.net/jquery/1.10.2/jquery.min.js">
</script>
<script> $(document).ready(function(){$("#flip").click(function(){$("#panel").slideToggle("slow");});});
</script>
<style type="text/css"> #panel,#flip {padding:5px;text-align:center;background-color:#e5eecc;border:solid 1px #c3c3c3;}#panel {padding:50px;display:none;}
</style>
</head>
<body><div id="flip">點我,顯示或隱藏面板。</div><div id="panel">Hello world!</div>
</body>

jQuery 效果- 動畫

animate() 方法

animate() 方法用于創建自定義動畫

<script src="https://cdn.staticfile.net/jquery/1.10.2/jquery.min.js">
</script>
<script> $(document).ready(function(){$("button").click(function(){$("div").animate({left:'250px'});});});
</script> 
</head>
<body><button>開始動畫</button><p>默認情況下,所有的 HTML 元素有一個靜態的位置,且是不可移動的。 如果需要改變為,我們需要將元素的 position 屬性設置為 relative, fixed, 或 absolute!</p><div style="background:#98bf21;height:100px;width:100px;position:absolute;"></div>
</body>
<script src="https://cdn.staticfile.net/jquery/1.10.2/jquery.min.js">
</script>
<script> $(document).ready(function(){$("button").click(function(){$("div").animate({left:'250px',opacity:'0.5',height:'150px',width:'150px'});});});
</script> 
</head>
<body><button>開始動畫</button><p>默認情況下,所有的 HTML 元素有一個靜態的位置,且是不可移動的。 如果需要改變,我們需要將元素的 position 屬性設置為 relative, fixed, 或 absolute!</p><div style="background:#98bf21;height:100px;width:100px;position:absolute;"></div>
</body>

animate() - 使用相對值

<script src="https://cdn.staticfile.net/jquery/1.10.2/jquery.min.js">
</script>
<script> $(document).ready(function(){$("button").click(function(){$("div").animate({left:'250px',height:'+=150px',width:'+=150px'});});});
</script> 
</head>
<body><button>開始動畫</button><p>默認情況下,所有的 HTML 元素有一個靜態的位置,且是不可移動的。 如果需要改變為,我們需要將元素的 position 屬性設置為 relative, fixed, 或 absolute!</p><div style="background:#98bf21;height:100px;width:100px;position:absolute;"></div>
</body>

animate() - 使用預定義的值

<script src="https://cdn.staticfile.net/jquery/1.10.2/jquery.min.js">
</script>
<script> $(document).ready(function(){$("button").click(function(){$("div").animate({height:'toggle'});});});
</script> 
</head>
<body><button>開始動畫</button><p>默認情況下,所有的 HTML 元素有一個靜態的位置,且是不可移動的。 如果需要改變為,我們需要將元素的 position 屬性設置為 relative, fixed, 或 absolute!</p><div style="background:#98bf21;height:100px;width:100px;position:absolute;"></div>
</body>

animate() - 使用隊列功能

<script src="https://cdn.staticfile.net/jquery/1.10.2/jquery.min.js">
</script>
<script> $(document).ready(function(){$("button").click(function(){var div=$("div");div.animate({height:'300px',opacity:'0.4'},"slow");div.animate({width:'300px',opacity:'0.8'},"slow");div.animate({height:'100px',opacity:'0.4'},"slow");div.animate({width:'100px',opacity:'0.8'},"slow");});});
</script> 
</head>
<body><button>開始動畫</button><p>默認情況下,所有的 HTML 元素有一個靜態的位置,且是不可移動的。 如果需要改變為,我們需要將元素的 position 屬性設置為 relative, fixed, 或 absolute!</p><div style="background:#98bf21;height:100px;width:100px;position:absolute;"></div>
</body>
<script src="https://cdn.staticfile.net/jquery/1.10.2/jquery.min.js">
</script>
<script> $(document).ready(function(){$("button").click(function(){var div=$("div");  div.animate({left:'100px'},"slow");div.animate({fontSize:'3em'},"slow");});});
</script> 
</head>
<body><button>開始動畫</button><p>默認情況下,所有的 HTML 元素有一個靜態的位置,且是不可移動的。 如果需要改變為,我們需要將元素的 position 屬性設置為 relative, fixed, 或 absolute!</p><div style="background:#98bf21;height:100px;width:200px;position:absolute;">HELLO</div></body>

jQuery 停止動畫

<script src="https://cdn.staticfile.net/jquery/1.10.2/jquery.min.js">
</script>
<script> $(document).ready(function(){$("#flip").click(function(){$("#panel").slideDown(5000);});$("#stop").click(function(){$("#panel").stop();});});
</script>
<style type="text/css"> #panel,#flip {padding:5px;text-align:center;background-color:#e5eecc;border:solid 1px #c3c3c3;}#panel {padding:50px;display:none;}
</style>
</head>
<body><button id="stop">停止滑動</button><div id="flip">點我向下滑動面板</div><div id="panel">Hello world!</div>
</body>

jQuery - 鏈(Chaining)

<script src="https://cdn.staticfile.net/jquery/1.10.2/jquery.min.js">
</script>
<script>$(document).ready(function() {$("button").click(function() {$("#p1").css("color","red").slideUp(2000).slideDown(2000);});});
</script>
</head>
<body><p id="p1">菜鳥教程!!</p><button>點我</button>
</body>

jQuery - 獲取內容和屬性

獲得內容 - text()、html() 以及 val()

  • text() - 設置或返回所選元素的文本內容

  • html() - 設置或返回所選元素的內容(包括 HTML 標簽)

  • val() - 設置或返回表單字段的值

<script src="https://cdn.staticfile.net/jquery/1.10.2/jquery.min.js">
</script>
<script>$(document).ready(function(){$("#btn1").click(function(){alert("Text: " + $("#test").text());});$("#btn2").click(function(){alert("HTML: " + $("#test").html());});});
</script>
</head>
<body><p id="test">這是段落中的 <b>粗體</b> 文本。</p><button id="btn1">顯示文本</button><button id="btn2">顯示 HTML</button>
</body>
<script src="https://cdn.staticfile.net/jquery/1.10.2/jquery.min.js">
</script>
<script>$(document).ready(function(){$("button").click(function(){alert("值為: " + $("#test").val());});});
</script>
</head>
<body><p>名稱: <input type="text" id="test" value="菜鳥教程"></p><button>顯示值</button>
</body>

獲取屬性 - attr()

<script src="https://cdn.staticfile.net/jquery/1.10.2/jquery.min.js">
</script>
<script>$(document).ready(function(){$("button").click(function(){alert($("#runoob").attr("href"));});});
</script>
</head>
<body><p><a href="http://www.runoob.com" id="runoob">菜鳥教程</a></p><button>顯示 href 屬性的值</button>
</body>

jQuery - 設置內容和屬性

設置內容 - text()、html() 以及 val()

<script src="https://cdn.staticfile.net/jquery/1.10.2/jquery.min.js">
</script>
<script>$(document).ready(function(){$("#btn1").click(function(){$("#test1").text("Hello world!");});$("#btn2").click(function(){$("#test2").html("<b>Hello world!</b>");});$("#btn3").click(function(){$("#test3").val("RUNOOB");});});
</script>
</head>
<body><p id="test1">這是一個段落。</p><p id="test2">這是另外一個段落。</p><p>輸入框: <input type="text" id="test3" value="菜鳥教程"></p><button id="btn1">設置文本</button><button id="btn2">設置 HTML</button><button id="btn3">設置值</button>
</body>

text()、html() 以及 val() 的回調函數

<script src="https://cdn.staticfile.net/jquery/1.10.2/jquery.min.js">
</script>
<script>$(document).ready(function(){$("#btn1").click(function(){$("#test1").text(function(i,origText){return "舊文本: " + origText + " 新文本: Hello world! (index: " + i + ")"; });});$("#btn2").click(function(){$("#test2").html(function(i,origText){return "舊 html: " + origText + " 新 html: Hello <b>world!</b> (index: " + i + ")"; });});});
</script>
</head>
<body><p id="test1">這是一個有 <b>粗體</b> 字的段落。</p><p id="test2">這是另外一個有 <b>粗體</b> 字的段落。</p><button id="btn1">顯示 新/舊 文本</button><button id="btn2">顯示 新/舊 HTML</button>
</body>

設置屬性 - attr()

<script src="https://cdn.staticfile.net/jquery/1.10.2/jquery.min.js">
</script>
<script>$(document).ready(function(){$("button").click(function(){$("#runoob").attr("href","http://www.runoob.com/jquery");});});
</script>
</head>
<body><p><a href="http://www.runoob.com" id="runoob">菜鳥教程</a></p><button>修改 href 值</button><p>點擊按鈕修改后,可以點擊鏈接查看鏈接地址是否變化。</p>
</body>
<script src="https://cdn.staticfile.net/jquery/1.10.2/jquery.min.js">
</script>
<script>$(document).ready(function(){$("button").click(function(){$("#runoob").attr({"href" : "http://www.runoob.com/jquery","title" : "jQuery 教程"});// 通過修改的 title 值來修改鏈接名稱title =  $("#runoob").attr('title');$("#runoob").html(title);});});
</script>
</head>
<body><p><a href="http://www.runoob.com" id="runoob">菜鳥教程</a></p><button>修改 href 和 title</button><p>點擊按鈕修改后,可以查看 href 和 title 是否變化。</p>
</body>

attr() 的回調函數

<script src="https://cdn.staticfile.net/jquery/1.10.2/jquery.min.js"></script>
<script>$(document).ready(function(){$("button").click(function(){$("#runoob").attr("href", function(i, origValue){return origValue + "/jquery";});});});
</script>
</head>
<body><p><a href="http://www.runoob.com" id="runoob">菜鳥教程</a></p><button>修改 href 值</button><p>點擊按鈕修改后,可以點擊鏈接查看 href 屬性是否變化。</p>
</body>

jQuery - 添加元素

jQuery append() 方法

方法在被選元素的結尾插入內容(仍然在該元素的內部)

<script src="https://cdn.staticfile.net/jquery/1.10.2/jquery.min.js">
</script>
<script>$(document).ready(function(){$("#btn1").click(function(){$("p").append(" <b>追加文本</b>。");});$("#btn2").click(function(){$("ol").append("<li>追加列表項</li>");});});
</script>
</head>
<body><p>這是一個段落。</p><p>這是另外一個段落。</p><ol><li>List item 1</li><li>List item 2</li><li>List item 3</li></ol><button id="btn1">添加文本</button><button id="btn2">添加列表項</button>
</body>

jQuery prepend() 方法

方法在被選元素的開頭插入內容

<script src="https://cdn.staticfile.net/jquery/1.10.2/jquery.min.js">
</script>
<script>$(document).ready(function(){$("#btn1").click(function(){$("p").prepend("<b>在開頭追加文本</b>。 ");});$("#btn2").click(function(){$("ol").prepend("<li>在開頭添加列表項</li>");});});
</script>
</head>
<body><p>這是一個段落。</p><p>這是另外一個段落。</p><ol><li>列表 1</li><li>列表 2</li><li>列表 3</li></ol><button id="btn1">添加文本</button><button id="btn2">添加列表項</button>
</body>

通過 append() 和 prepend() 方法添加若干新元素

<script src="https://cdn.staticfile.net/jquery/1.10.2/jquery.min.js">
</script>
<script>function appendText(){var txt1="<p>文本-1。</p>";              // 使用 HTML 標簽創建文本var txt2=$("<p></p>").text("文本-2。");  // 使用 jQuery 創建文本var txt3=document.createElement("p");txt3.innerHTML="文本-3。";               // 使用 DOM 創建文本 text with DOM$("body").append(txt1,txt2,txt3);        // 追加新元素}
</script>
</head>
<body><p>這是一個段落。</p><button οnclick="appendText()">追加文本</button>
</body>

jQuery after() 和 before() 方法

jQuery after() 方法在被選元素之后插入內容

jQuery before() 方法在被選元素之前插入內容

<script src="https://cdn.staticfile.net/jquery/1.10.2/jquery.min.js">
</script>
<script>$(document).ready(function(){$("#btn1").click(function(){$("img").before("<b>之前</b>");});$("#btn2").click(function(){$("img").after("<i>之后</i>");});});
</script>
</head>
<body><img src="/images/logo.png" ><br><br><button id="btn1">之前插入</button><button id="btn2">之后插入</button>
</body>
<script src="https://cdn.staticfile.net/jquery/1.10.2/jquery.min.js">
</script>
<script>function afterText(){var txt1="<b>I </b>";                    // 使用 HTML 創建元素var txt2=$("<i></i>").text("love ");     // 使用 jQuery 創建元素var txt3=document.createElement("big");  // 使用 DOM 創建元素txt3.innerHTML="jQuery!";$("img").after(txt1,txt2,txt3);          // 在圖片后添加文本}
</script>
</head>
<body><img src="/images/logo2.png" ><br><br><button οnclick="afterText()">之后插入</button>
</body>

jQuery - 刪除元素

jQuery remove() 方法

jQuery remove() 方法刪除被選元素及其子元素

<script src="https://cdn.staticfile.net/jquery/1.10.2/jquery.min.js">
</script>
<script>$(document).ready(function(){$("button").click(function(){$("#div1").remove();});});
</script>
</head>
<body><div id="div1" style="height:100px;width:300px;border:1px solid black;background-color:yellow;">這是 div 中的一些文本。<p>這是在 div 中的一個段落。</p><p>這是在 div 中的另外一個段落。</p></div><br><button>移除div元素</button>
</body>

jQuery empty() 方法

jQuery empty() 方法刪除被選元素的子元素

<script src="https://cdn.staticfile.net/jquery/1.10.2/jquery.min.js">
</script>
<script>$(document).ready(function(){$("button").click(function(){$("#div1").empty();});});
</script>
</head>
<body><div id="div1" style="height:100px;width:300px;border:1px solid black;background-color:yellow;">這是 div 中的一些文本。<p>這是在 div 中的一個段落。</p><p>這是在 div 中的另外一個段落。</p></div><br><button>清空div元素</button>
</body>

過濾被刪除的元素

jQuery remove() 方法也可接受一個參數,允許您對被刪元素進行過濾

<script src="https://cdn.staticfile.net/jquery/1.10.2/jquery.min.js">
</script>
<script>$(document).ready(function(){$("button").click(function(){$("p").remove(".italic");});});
</script> 
</head>
<body><p>這是一個段落。</p><p class="italic"><i>這是另外一個段落。</i></p><p class="italic"><i>這是另外一個段落。</i></p><button>移除所有  class="italic" 的 p 元素。</button>
</body>

jQuery - 獲取并設置 CSS 類

  • addClass() - 向被選元素添加一個或多個類

  • removeClass() - 從被選元素刪除一個或多個類

  • toggleClass() - 對被選元素進行添加/刪除類的切換操作

  • css() - 設置或返回樣式屬性

jQuery addClass() 方法

<script src="https://cdn.staticfile.net/jquery/1.10.2/jquery.min.js">
</script>
<script>$(document).ready(function(){$("button").click(function(){$("h1,h2,p").addClass("blue");$("div").addClass("important blue");});});
</script>
<style type="text/css">.important {font-weight:bold;font-size:xx-large;}.blue {color:blue;}
</style>
</head>
<body><h1>標題 1</h1><h2>標題 2</h2><p>這是一個段落。</p><p>這是另外一個段落。</p><div>這是一些重要的文本!</div> <br><button>為元素添加 class</button>
</body>

jQuery removeClass() 方法

<script src="https://cdn.staticfile.net/jquery/1.10.2/jquery.min.js">
</script>
<script>$(document).ready(function(){$("button").click(function(){$("h1,h2,p").removeClass("blue");});});
</script>
<style type="text/css">.important {font-weight:bold;font-size:xx-large;}.blue {color:blue;}
</style>
</head>
<body><h1 class="blue">標題 1</h1><h2 class="blue">標題 2</h2><p class="blue">這是一個段落。</p><p class="important">這是另外一個段落。</p><br><button>從元素中移除 class</button>
</body>

jQuery toggleClass() 方法

<script src="https://cdn.staticfile.net/jquery/1.10.2/jquery.min.js">
</script>
<script>$(document).ready(function(){$("button").click(function(){$("h1,h2,p").toggleClass("blue");});});
</script>
<style type="text/css">.blue {color:blue;}
</style>
</head>
<body><h1 class="blue">標題 1</h1><h2 class="blue">標題 2</h2><p class="blue">這是一個段落。</p><p>這是另外一個段落。</p><br><button>切換 class</button>
</body>

jQuery css() 方法

返回 CSS 屬性

<script src="https://cdn.staticfile.net/jquery/1.10.2/jquery.min.js">
</script>
<script>$(document).ready(function(){$("button").click(function(){alert("背景顏色 = " + $("p").css("background-color"));});});
</script>
</head>
<body><h2>這是一個標題</h2><p style="background-color:#ff0000">這是一個段落。</p><p style="background-color:#00ff00">這是一個段落。</p><p style="background-color:#0000ff">這是一個段落。</p><button>返回第一個 p 元素的 background-color </button>
</body>

設置 CSS 屬性

<script src="https://cdn.staticfile.net/jquery/1.10.2/jquery.min.js">
</script>
<script>$(document).ready(function(){$("button").click(function(){$("p").css("background-color","yellow");});});
</script>
</head>
<body><h2>這是一個標題</h2><p style="background-color:#ff0000">這是一個段落。</p><p style="background-color:#00ff00">這是一個段落。</p><p style="background-color:#0000ff">這是一個段落。</p><p>這是一個段落。</p><button>設置 p 元素的 background-color </button>
</body>

設置多個 CSS 屬性

<script src="https://cdn.staticfile.net/jquery/1.10.2/jquery.min.js">
</script>
<script>$(document).ready(function(){$("button").click(function(){$("p").css({"background-color":"yellow","font-size":"200%"});});});
</script>
</head>
<body><h2>這是一個標題</h2><p style="background-color:#ff0000">這是一個段落。</p><p style="background-color:#00ff00">這是一個段落。</p><p style="background-color:#0000ff">這是一個段落。</p><p>這是一個段落。</p><button>為 p 元素設置多個樣式</button>
</body>

jQuery 尺寸

width() height() innerWidth() innerHeight()

width() 方法設置或返回元素的寬度(不包括內邊距、邊框或外邊距)

height() 方法設置或返回元素的高度(不包括內邊距、邊框或外邊距)

innerWidth() 方法返回元素的寬度(包括內邊距)

innerHeight() 方法返回元素的高度(包括內邊距)

<script src="https://cdn.staticfile.net/jquery/1.10.2/jquery.min.js">
</script>
<script>$(document).ready(function(){$("button").click(function(){var txt="";txt+="div 寬度: " + $("#div1").width() + "</br>";txt+="div 高度: " + $("#div1").height() + "</br>";txt+="div 寬度,包含內邊距: " + $("#div1").innerWidth() + "</br>";txt+="div 高度,包含內邊距: " + $("#div1").innerHeight();$("#div1").html(txt);});});
</script>
</head>
<body><div id="div1" style="height:100px;width:300px;padding:10px;margin:3px;border:1px solid blue;background-color:lightblue;"></div><br><button>顯示 div 元素的尺寸</button><p>innerWidth() - 返回元素的寬度 (包含內邊距)。</p><p>innerHeight() - 返回元素的高度 (包含內邊距)。</p>
</body>

jQuery outerWidth() 和 outerHeight() 方法

outerWidth() 方法返回元素的寬度(包括內邊距和邊框)

outerHeight() 方法返回元素的高度(包括內邊距和邊框)

<script src="https://cdn.staticfile.net/jquery/1.10.2/jquery.min.js">
</script>
<script>$(document).ready(function(){$("button").click(function(){var txt="";txt+="div 寬度: " + $("#div1").width() + "</br>";txt+="div 高度: " + $("#div1").height() + "</br>";txt+="div 寬度,包含內邊距和邊框: " + $("#div1").outerWidth() + "</br>";txt+="div 高度,包含內邊距和邊框: " + $("#div1").outerHeight();$("#div1").html(txt);});});
</script>
</head>
<body><div id="div1" style="height:100px;width:300px;padding:10px;margin:3px;border:1px solid blue;background-color:lightblue;"></div><br><button>顯示 div 元素的尺寸</button><p>outerWidth() - 返回元素的寬度 (包含內邊距和邊框)。</p><p>outerHeight() - 返回元素的高度 (包含內邊距和邊框)。</p>
</body>

jQuery 遍歷 - 祖先

jQuery parent() 方法

parent() 方法返回被選元素的直接父元素

<style>.ancestors *{ display: block;border: 2px solid lightgrey;color: lightgrey;padding: 5px;margin: 15px;}
</style>
<script src="https://cdn.staticfile.net/jquery/1.10.2/jquery.min.js">
</script>
<script>$(document).ready(function(){$("span").parent().css({"color":"red","border":"2px solid red"});});
</script>
</head>
<body><div class="ancestors"><div style="width:500px;">div (曾祖父元素)<ul>ul (祖父元素)  <li>li (父元素)<span>span</span></li></ul>   </div><div style="width:500px;">div (祖父元素)   <p>p (父元素)<span>span</span></p> </div></div>
</body>

jQuery parents() 方法

parents() 方法返回被選元素的所有祖先元素,它一路向上直到文檔的根元素 (<html>)

<style>.ancestors * { display: block;border: 2px solid lightgrey;color: lightgrey;padding: 5px;margin: 15px;}
</style>
<script src="https://cdn.staticfile.net/jquery/1.10.2/jquery.min.js">
</script>
<script>$(document).ready(function(){$("span").parents().css({"color":"red","border":"2px solid red"});});
</script>
</head>
<body class="ancestors">body (曾曾祖父元素)<div style="width:500px;">div (曾祖父元素)<ul>ul (祖父元素)  <li>li (父元素)<span>span</span></li></ul>   </div>
</body>
$(document).ready(function(){$("span").parents("ul");
});

jQuery parentsUntil() 方法

parentsUntil() 方法返回介于兩個給定元素之間的所有祖先元素

<style>.ancestors * { display: block;border: 2px solid lightgrey;color: lightgrey;padding: 5px;margin: 15px;}
</style>
<script src="https://cdn.staticfile.net/jquery/1.10.2/jquery.min.js">
</script>
<script>$(document).ready(function(){$("span").parentsUntil("div").css({"color":"red","border":"2px solid red"});});
</script>
</head>
<body class="ancestors"> body (曾曾祖父元素)<div style="width:500px;">div (曾祖父元素)<ul>ul (祖父元素)  <li>li (父元素)<span>span</span></li></ul>   </div>
</body>

jQuery 遍歷 - 后代

jQuery children() 方法

children() 方法返回被選元素的所有直接子元素

<style>.descendants * { display: block;border: 2px solid lightgrey;color: lightgrey;padding: 5px;margin: 15px;}
</style>
<script src="https://cdn.staticfile.net/jquery/1.10.2/jquery.min.js">
</script>
<script>$(document).ready(function(){$("div").children("p.1").css({"color":"red","border":"2px solid red"});// $("div").children().css({"color":"red","border":"2px solid red"});});
</script>
</head>
<body><div class="descendants" style="width:500px;">div (當前元素) <p class="1">p (兒子元素)<span>span (孫子元素)</span>     </p><p class="2">p (兒子元素)<span>span (孫子元素)</span></p> </div>
</body>

jQuery find() 方法

find() 方法返回被選元素的后代元素,一路向下直到最后一個后代

<!-- 返回屬于 <div> 后代的所有 <span> 元素 -->
<style>.descendants * { display: block;border: 2px solid lightgrey;color: lightgrey;padding: 5px;margin: 15px;}
</style>
<script src="https://cdn.staticfile.net/jquery/1.10.2/jquery.min.js">
</script>
<script>$(document).ready(function(){$("div").find("span").css({"color":"red","border":"2px solid red"});// 返回 <div> 的所有后代// $("div").find("*").css({"color":"red","border":"2px solid red"});});
</script>
</head>
<body><div class="descendants" style="width:500px;">div (當前元素) <p>p (兒子元素)<span>span (孫子元素)</span>     </p><p>p (兒子元素)<span>span (孫子元素)</span></p> </div>
</body>

jQuery 遍歷 - 同胞(siblings)

jQuery siblings() 方法

siblings() 方法返回被選元素的所有同胞元素

<style>.siblings * { display: block;border: 2px solid lightgrey;color: lightgrey;padding: 5px;margin: 15px;}
</style>
<script src="https://cdn.staticfile.net/jquery/1.10.2/jquery.min.js">
</script>
<script>$(document).ready(function(){$("h2").siblings().css({"color":"red","border":"2px solid red"});// $("h2").siblings("p");  // 返回屬于 <h2> 的同胞元素的所有 <p> 元素});
</script>
</head>
<body class="siblings"><div>div (父元素)<p>p</p><span>span</span><h2>h2</h2><h3>h3</h3><p>p</p></div>
</body>

jQuery next() 方法

next() 方法返回被選元素的下一個同胞元素

<script>$(document).ready(function(){$("h2").next();});
</script>

jQuery nextAll() 方法

nextAll() 方法返回被選元素的所有跟隨的同胞元素

<style>.siblings * { display: block;border: 2px solid lightgrey;color: lightgrey;padding: 5px;margin: 15px;}
</style>
<script src="https://cdn.staticfile.net/jquery/1.10.2/jquery.min.js">
</script>
<script>$(document).ready(function(){$("h2").nextAll().css({"color":"red","border":"2px solid red"});});
</script>
</head>
<body class="siblings"><div>div (父元素)<p>p</p><span>span</span><h2>h2</h2><h3>h3</h3><p>p</p></div>
</body>

jQuery nextUntil() 方法

nextUntil() 方法返回介于兩個給定參數之間的所有跟隨的同胞元素

<script>$(document).ready(function(){$("h2").nextUntil("h6");});
</script>

jQuery prev(), prevAll() & prevUntil() 方法

prev(), prevAll() 以及 prevUntil() 方法的工作方式與上面的方法類似,只不過方向相反而已:它們返回的是前面的同胞元素(在 DOM 樹中沿著同胞之前元素遍歷,而不是之后元素遍歷)

jQuery 遍歷- 過濾

jQuery first() 方法

first() 方法返回被選元素的首個元素

<script>$(document).ready(function(){$("div p").first();});
</script>

jQuery last() 方法

last() 方法返回被選元素的最后一個元素

<script>$(document).ready(function(){$("div p").last();});
</script>

jQuery eq() 方法

eq() 方法返回被選元素中帶有指定索引號的元素

<script src="https://cdn.staticfile.net/jquery/1.10.2/jquery.min.js">
</script>
<script>$(document).ready(function(){$("p").eq(1).css("background-color","yellow");});
</script>
</head>
<body><h1>歡迎訪問我的主頁</h1><p>菜鳥教程 (index 0).</p><p>http://www.runoob.com (index 1)。</p><p>google (index 2).</p><p>http://www.google.com (index 3)。</p>
</body>

jQuery filter() 方法

filter() 方法允許您規定一個標準。不匹配這個標準的元素會被從集合中刪除,匹配的元素會被返回

<script src="https://cdn.staticfile.net/jquery/1.10.2/jquery.min.js">
</script>
<script>$(document).ready(function(){$("p").filter(".url").css("background-color","yellow");});
</script>
</head>
<body><h1>歡迎訪問我的主頁</h1><p>菜鳥教程 (index 0).</p><p class="url">http://www.runoob.com (index 1)。</p><p>google (index 2).</p><p class="url">http://www.google.com (index 3)。</p>
</body>

jQuery not() 方法

not() 方法返回不匹配標準的所有元素,not() 方法與 filter() 相反

<script>$(document).ready(function(){$("p").not(".url");});
</script>

jQuery - AJAX load() 方法

<script src="https://cdn.staticfile.net/jquery/1.10.2/jquery.min.js">
</script>
<script>$(document).ready(function(){$("button").click(function(){$("#div1").load("/try/ajax/demo_test.txt");});});
</script>
</head>
<body><div id="div1"><h2>使用 jQuery AJAX 修改文本內容</h2></div><button>獲取外部內容</button>
</body>

load() 方法從服務器加載數據,并把返回的數據放入被選元素中

$(selector).load(URL,data,callback);

必需的 URL 參數規定您希望加載的 URL

可選的 data 參數規定與請求一同發送的查詢字符串鍵/值對集合

可選的 callback 參數是 load() 方法完成后所執行的函數名稱

這是示例文件("demo_test.txt")的內容:

<h2>jQuery AJAX 是個非常棒的功能!</h2>
<p id="p1">這是段落的一些文本</p>
$("#div1").load("demo_test.txt");
$("#div1").load("demo_test.txt #p1");

可選的 callback 參數規定當 load() 方法完成后所要允許的回調函數。回調函數可以設置不同的參數:

  • responseTxt - 包含調用成功時的結果內容

  • statusTXT - 包含調用的狀態

  • xhr - 包含 XMLHttpRequest 對象

<script src="https://cdn.staticfile.net/jquery/1.10.2/jquery.min.js">
</script>
<script>$(document).ready(function(){$("button").click(function(){$("#div1").load("/try/ajax/demo_test.txt",function(responseTxt,statusTxt,xhr){if(statusTxt=="success")alert("外部內容加載成功!");if(statusTxt=="error")alert("Error: "+xhr.status+": "+xhr.statusText);});});});
</script>
</head>
<body><div id="div1"><h2>使用 jQuery AJAX 修改該文本</h2></div><button>獲取外部內容</button>
</body>

jQuery - AJAX get() 和 post() 方法

jQuery $.get() 方法

<script>$.get(URL,callback);// 或$.get( URL [, data ] [, callback ] [, dataType ] )
</script>
  • URL:發送請求的 URL字符串

  • data:可選的,發送給服務器的字符串或 key/value 鍵值對

  • callback:可選的,請求成功后執行的回調函數

  • dataType:可選的,從服務器返回的數據類型。默認:智能猜測(可以是xml, json, script, 或 html)

<script src="https://cdn.staticfile.net/jquery/1.10.2/jquery.min.js">
</script>
<script>$(document).ready(function(){$("button").click(function(){$.get("/try/ajax/demo_test.php",function(data,status){alert("數據: " + data + "\n狀態: " + status);});});});
</script>
</head>
<body><button>發送一個 HTTP GET 請求并獲取返回結果</button>
</body>

jQuery $.post() 方法

$.post() 方法通過 HTTP POST 請求向服務器提交數據。

語法:

<script>$.post(URL,callback);// 或$.post( URL [, data ] [, callback ] [, dataType ] )
</script>
<script src="https://cdn.staticfile.net/jquery/1.10.2/jquery.min.js">
</script>
<script>$(document).ready(function(){$("button").click(function(){$.post("/try/ajax/demo_test_post.php",{name:"菜鳥教程",url:"http://www.runoob.com"},function(data,status){alert("數據: \n" + data + "\n狀態: " + status);});});});
</script>
</head>
<body><button>發送一個 HTTP POST 請求頁面并獲取返回內容</button>
</body>
<?php$name = isset($_POST['name']) ? htmlspecialchars($_POST['name']) : '';
$url = isset($_POST['url']) ? htmlspecialchars($_POST['url']) : '';
echo '網站名: ' . $name;
echo "\n";
echo 'URL 地址: ' .$url;
?># demo_test_post.php

jQuery - noConflict() 方法

jQuery 使用 $ 符號作為 jQuery 的簡寫

如果其他 JavaScript 框架也使用 $ 符號作為簡寫怎么辦?

<script src="https://cdn.staticfile.net/jquery/1.10.2/jquery.min.js">
</script>
<script>$.noConflict();jQuery(document).ready(function(){jQuery("button").click(function(){jQuery("p").text("jQuery 仍然在工作!");});});
</script>
</head>
<body><p>這是一個段落</p><button>點我</button>
</body>
<script src="https://cdn.staticfile.net/jquery/1.10.2/jquery.min.js">
</script>
<script>var jq=$.noConflict();jq(document).ready(function(){jq("button").click(function(){jq("p").text("jQuery 仍然在工作!");});});
</script>
</head>
<body><p>這是一個段落。</p><button>點我</button>
</body>
<script src="https://cdn.staticfile.net/jquery/1.10.2/jquery.min.js">
</script>
<script>$.noConflict();jQuery(document).ready(function($){$("button").click(function(){$("p").text("jQuery 仍然在工作!");});});
</script>
</head>
<body><p>這是一個段落。</p><button>點我</button>
</body>

JSONP 教程

Jsonp(JSON with Padding) 是 json 的一種"使用模式",可以讓網頁從別的域名(網站)那獲取資料,即跨域讀取數據

JSONP 應用

1. 服務端 JSONP 格式數據

如客戶想訪問 : https://www.runoob.com/try/ajax/jsonp.php?jsoncallback=callbackFunction

假設客戶期望返回數據:["customername1","customername2"]

真正返回到客戶端的數據顯示為: callbackFunction(["customername1","customername2"])

服務端文件 jsonp.php 代碼為:

<?phpheader('Content-type: application/json');
//獲取回調函數名
$jsoncallback = htmlspecialchars($_REQUEST ['jsoncallback']);
//json數據
$json_data = '["customername1","customername2"]';
//輸出jsonp格式的數據
echo $jsoncallback . "(" . $json_data . ")";
?># jsonp.php

2. 客戶端實現 callbackFunction 函數

<script type="text/javascript">function callbackFunction(result, methodName) {var html = '<ul>';for(var i = 0; i < result.length; i++) {html += '<li>' + result[i] + '</li>';}html += '</ul>';document.getElementById('divCustomers').innerHTML = html;}
</script>

頁面展示

<div id="divCustomers"></div>

客戶端頁面完整代碼

<!DOCTYPE html>
<html><head><meta charset="utf-8"><title>JSONP 實例</title></head><body><div id="divCustomers"></div><script type="text/javascript">function callbackFunction(result, methodName) {var html = '<ul>';for(var i = 0; i < result.length; i++) {html += '<li>' + result[i] + '</li>';}html += '</ul>';document.getElementById('divCustomers').innerHTML = html;}</script><script type="text/javascript" src="https://www.runoob.com/try/ajax/jsonp.php?jsoncallback=callbackFunction"></script></body>
</html>

jQuery 使用 JSONP

以上代碼可以使用 jQuery 代碼實例:

<!DOCTYPE html>
<html><head><meta charset="utf-8"><title>JSONP 實例</title><script src="https://cdn.static.runoob.com/libs/jquery/1.8.3/jquery.js"></script>    </head><body><div id="divCustomers"></div><script>$.getJSON("https://www.runoob.com/try/ajax/jsonp.php?jsoncallback=?", function(data) {var html = '<ul>';for(var i = 0; i < data.length; i++) {html += '<li>' + data[i] + '</li>';}html += '</ul>';$('#divCustomers').html(html); });</script></body>
</html>

jQuery 插件

jQuery Validate | 菜鳥教程 (runoob.com)

jQuery 實例

jQuery 選擇器

$(this).hide()

演示 jQuery 的 hide() 函數,隱藏當前的 HTML 元素。

$("p").hide()

演示 jQuery 的 hide() 函數,隱藏所有 <p> 元素。

$(".test").hide()

演示 jQuery 的 hide() 函數,隱藏所有 class="test" 的元素。

$("#test").hide()

演示 jQuery 的 hide() 函數,隱藏 id="test" 的元素。


jQuery 事件

jQuery click() 演示 jQuery jQuery click() 事件.

jQuery dblclick() 演示 jQuery dblclick() 事件。

jQuery mouseenter() 演示 jQuery mouseenter() 事件。

jQuery mouseleave() 演示 jQuery mouseleave() 事件。

jQuery mousedown() 演示 jQuery mousedown() 事件。

jQuery mouseup() 演示 jQuery mouseup() 事件。

jQuery hover() 演示 jQuery hover() 事件。

jQuery focus() 和 blur() 演示 jQuery focus() 和 blur() 事件。

實例解析


jQuery 隱藏/顯示

jQuery hide() 演示 jQuery hide() 方法。

jQuery hide() 和 show() 演示jQuery hide() 和 show() 方法。

jQuery toggle() jQuery toggle() 用于切換 hide() 和 show() 方法。

jQuery hide() 另外一個隱藏文本的實例。

實例解析


jQuery 淡入淡出

jQuery fadeIn() 演示 jQuery fadeIn() 方法。

jQuery fadeOut() 演示 jQuery fadeOut() 方法。

jQuery fadeToggle() 演示 jQuery fadeToggle() 方法。

jQuery fadeTo() 演示 jQuery fadeTo() 方法。

實例解析


jQuery 滑動

jQuery slideDown() 演示 jQuery slideDown() 方法。

jQuery slideUp() 演示 jQuery slideUp() 方法。

jQuery slideToggle() 演示 jQuery slideToggle() 方法。

實例解析


jQuery 動畫

jQuery animate() 演示簡單的 jQuery animate() 方法。

jQuery animate() - 設置多個css屬性 演示通過 jQuery animate() 方法 改變樣式。

jQuery animate() - 使用相關值 演示如何在 jQuery animate() 方法中使用相關值。

jQuery animate() - 使用預定義值 演示通過 animate() 方法預定義 "hide", "show", "toggle" 值。

jQuery animate() 演示更多 jQuery animate() 方法實例

jQuery animate() 演示更多 jQuery animate() 方法實例 (多個 animate() 回調).

實例 解析


jQuery 停止動畫

jQuery stop() 滑動 演示 jQuery stop() 方法。

jQuery stop() 動畫 (帶參數) 演示 jQuery stop() 方法。

實例解析


jQuery HTML 獲取 和 屬性

jQuery text() 和 html() - 獲取文本和內容 使用jQuery text() 和 html() 方法獲取內容。

jQuery val() - 獲取值 使用jQuery val() 方法獲取表單的字段值。

jQuery attr() - 獲取屬性值 使用jQuery attr() 方法獲取屬性值。

實例解析


jQuery HTML 設置內容和屬性

jQuery text(), html(), 和 val() - 設置內容 使用 jQuery text(), html() 和 val() 方法設置內容 。

jQuery text() 和 html() - 設置內容并使用回調函數 使用 text() 和 html() 設置內容并使用回調函數

jQuery attr() - 設置屬性值 使用 jQuery attr() 方法設置屬性值 。

jQuery attr() - 設置 多個屬性值 使用jQuery attr() 方法設置多個屬性值。

jQuery attr() - 設置屬性值并使用回調函數 設置屬性值 + 并使用回調函數調用attr().

實例解析


jQuery HTML 添加元素/內容

jQuery append() 在選取元素的末尾添加內容

jQuery prepend() 在選取元素的開頭添加內容

jQuery append() -插入多個元素 創新新的 text/HTML 元素, jQuery 和 JavaScript/DOM。添加在新元素文本后。

jQuery after() 和 before() 在選取元素的前后添加 HTML 元素。

jQuery after() - 插入多個元素 創新新的 text/HTML 元素,jQuery和 JavaScript/DOM。在選取元素的末尾插入新元素。

實例解析


jQuery HTML 移除元素/內容

jQuery remove() 移除選取的元素

jQuery empty() 移除選取元素的所有子元素

jQuery remove() - 使用參數 過濾元素并移除

實例解析


jQuery Get 和 設置 CSS 類

jQuery addClass() 不同元素添加 class 屬性

jQuery addClass() - 多個類 使用 addClass() 方法添加多個類

jQuery removeClass() 移除指定元素的類

jQuery toggleClass() 在選取的元素切換(添加/刪除)類

實例解析


jQuery css() 方法

jQuery css() - 返回 CSS 屬性 返回第一個匹配元素的css屬性值

jQuery css() - 設置 CSS 屬性 設置 所有配置元素指定的 CSS 屬性

jQuery css() - 設置 CSS 屬性 設置多個匹配元素的 CSS 屬性

實例解析


jQuery 尺寸

jQuery - 返回 width() 和 height() 返回指定元素的 width 和 height

jQuery - 返回 innerWidth() 和 innerHeight() 返回指定元素的 inner-width/height

jQuery - 返回 outerWidth() 和 outerHeight() 返回指定元素的 outer-width/height

jQuery - 返回 outerWidth(true) 和 outerHeight(true) 返回指定元素的 outer-width/height (包含外邊框)

jQuery - 返回 width() 和 height() of document 和 window 返回 HTML 文檔和窗口的 width 和 height

jQuery - 設置 width() 和 height() 設置指定元素的 width 和 height

實例解析


jQuery 遍歷 - 祖先

jQuery parent() 演示 jQuery parent() 方法。

jQuery parents() 演示 jQuery parents() 方法。

jQuery parentsUntil() 演示 jQuery parentsUntil() 方法。

實例解析


jQuery 遍歷 - 后代

jQuery children() 演示 jQuery children() 方法。

jQuery find() 演示 jQuery find() 方法。

實例解析


jQuery 遍歷 - 同胞(siblings)

jQuery siblings() 演示 jQuery siblings() 方法。

jQuery next() 演示 jQuery next() 方法。

jQuery nextAll() 演示 jQuery nextAll() 方法。

jQuery nextUntil() 演示 jQuery nextUntil() 方法。

實例解析


jQuery AJAX load() 方法

jQuery load() 異步載入文件內容并插入到 <div> 元素中。

jQuery load() 異步載入文件內容中指定的元素內容并插入到 <div> 元素.

jQuery load() - 使用回調函數(callback) 使用 jQuery load() 方法的回調函數。

實例解析


jQuery AJAX get() 和 post() 方法

jQuery get() 使用 $.get() 方法從服務端異步獲取數據

jQuery post() 使用 $.post() 方法從服務端異步獲取數據

實例解析


其他實例

jQuery 動態粒子效果

Elasticsearch搜索引擎

es安裝

# 拉取鏡像
docker pull elasticsearch:7.12.0
# 創建docker容器掛載在的目錄
# linux的命令
mkdir -p /opt/es/config & mkdir -p /opt/es/data & mkdir -p /opt/es/plugins
chmod 777 /opt/es/data
# 配置文件
echo "http.host: 0.0.0.0" > /opt/es/config/elasticsearch.yml
# 創建容器
# linux
docker run --name es -p 9200:9200 ?-p 9300:9300 -e "discovery.type=single-node" -e ES_JAVA_OPTS="-Xms84m -Xmx512m" -v /opt/es/config/elasticsearch.yml:/usr/share/elasticsearch/config/elasticsearch.yml -v /opt/es/data:/usr/share/elasticsearch/data -v /opt/es/plugins:/usr/share/elasticsearch/plugins -d elasticsearch:7.12.0
# windows
docker run --name es -p 9200:9200 ?-p 9300:9300 -e "discovery.type=single-node" -e ES_JAVA_OPTS="-Xms84m -Xmx512m" -v H:\\docker\\es\\config\\elasticsearch.yml:/usr/share/elasticsearch/config/elasticsearch.yml -v H:\\docker\\es\\data:/usr/share/elasticsearch/data -v H:\\docker\\es\\plugins:/usr/share/elasticsearch/plugins -d elasticsearch:7.12.0
# windows添加目錄映射,需要在dockerDesktop里面設置映射目錄

訪問ip:9200能看到東西就說明安裝成功了

瀏覽器可以下載一個 Multi Elasticsearch Head es插件

或者這個ElasticHD

連接es

package core
import ("es_study/global""fmt""github.com/olivere/elastic/v7"
)
?
func EsConnect() {client, err := elastic.NewClient(elastic.SetURL("http://127.0.0.1:9200"),elastic.SetSniff(false),elastic.SetBasicAuth("", ""),)if err != nil {fmt.Println(err)return}global.ESClient = client
}

es認證

不需要認證的情況

  1. 服務器自己使用,9200,9300端口不對外開放

  2. 本身跑在127.0.0.1上

需要認證的情況:

  1. es需要對外提供服務的

給docker創建的elasticsearch容器添加密碼_docker elasticsearch 設置密碼-CSDN博客

img

這樣就說明成功了

輸入用戶名和密碼就能看到之前的那個頁面

或者使用curl進行測試

curl ?http://127.0.0.1:9200/
curl -u elastic:xxxxxx http://127.0.0.1:9200/

索引操作

mapping

// 查看某個索引的map
/index/_mapping

常見的類型

{"mappings": {"properties": {"title": { "type": "text" // 查詢的時候是分詞匹配},"key": { "type": "keyword" // 完整匹配},"user_id": {"type": "integer"},"created_at":{"type": "date","null_value": "null","format": "[yyyy-MM-dd HH:mm:ss]"}}}
}

創建索引

func CreateIndex() {createIndex, err := global.ESClient.CreateIndex("user_index").BodyString(models.UserModel{}.Mapping()).Do(context.Background())if err != nil {fmt.Println(err)return}fmt.Println(createIndex)fmt.Println("索引創建成功")
}

注意:索引存在執行創建索引是會報錯的

判斷索引是否存在

// ExistsIndex 判斷索引是否存在
func ExistsIndex(index string) bool {exists, _ := global.ESClient.IndexExists(index).Do(context.Background())return exists
}

刪除索引

func DeleteIndex(index string) {_, err := global.ESClient.DeleteIndex(index).Do(context.Background())if err != nil {fmt.Println(err)return}fmt.Println(index, "索引刪除成功")
}

文檔操作

添加文檔

添加單個文檔
func DocCreate() {user := models.UserModel{ID:        12,UserName:  "lisi",Age:       23,NickName:  "夜空中最亮的lisi",CreatedAt: time.Now().Format("2006-01-02 15:04:05"),Title:     "今天天氣很不錯",}indexResponse, err := global.ESClient.Index().Index(user.Index()).BodyJson(user).Do(context.Background())if err != nil {fmt.Println(err)return}fmt.Printf("%#v\n", indexResponse)
}

添加文檔

如果是mapping里面沒有的字段,那么es會自動創建這個字段對應的mapping

批量添加
func DocCreateBatch() {list := []models.UserModel{{ID:        12,UserName:  "fengfeng",NickName:  "夜空中最亮的楓楓",CreatedAt: time.Now().Format("2006-01-02 15:04:05"),},{ID:        13,UserName:  "lisa",NickName:  "夜空中最亮的麗薩",CreatedAt: time.Now().Format("2006-01-02 15:04:05"),},}bulk := global.ESClient.Bulk().Index(models.UserModel{}.Index()).Refresh("true")for _, model := range list {req := elastic.NewBulkCreateRequest().Doc(model)bulk.Add(req)}res, err := bulk.Do(context.Background())if err != nil {fmt.Println(err)return}fmt.Println(res.Succeeded())
}

刪除文檔

根據id刪除
func DocDelete() {deleteResponse, err := global.ESClient.Delete().Index(models.UserModel{}.Index()).Id("tmcqfYkBWS69Op6Q4Z0t").Refresh("true").Do(context.Background())if err != nil {fmt.Println(err)return}fmt.Println(deleteResponse)
}

如果文檔不存在,會報404的錯誤

根據id批量刪除
func DocDeleteBatch() {idList := []string{"tGcofYkBWS69Op6QHJ2g","tWcpfYkBWS69Op6Q050w",}bulk := global.ESClient.Bulk().Index(models.UserModel{}.Index()).Refresh("true")for _, s := range idList {req := elastic.NewBulkDeleteRequest().Id(s)bulk.Add(req)}res, err := bulk.Do(context.Background())if err != nil {fmt.Println(err)return}fmt.Println(res.Succeeded())  // 實際刪除的文檔切片
}

如果文檔不存在,不會有錯誤, res.Succeeded() 為空

文檔查詢

列表查詢
func DocFind() {limit := 2page := 4from := (page - 1) * limitquery := elastic.NewBoolQuery()res, err := global.ESClient.Search(models.UserModel{}.Index()).Query(query).From(from).Size(limit).Do(context.Background())if err != nil {fmt.Println(err)return}count := res.Hits.TotalHits.Value  // 總數fmt.Println(count)for _, hit := range res.Hits.Hits {fmt.Println(string(hit.Source))}
}
精確匹配

針對keyword字段

query := elastic.NewTermQuery("user_name", "fengfeng")
模糊匹配

主要是查text,也能查keyword

模糊匹配keyword字段,是需要查完整的

匹配text字段則不用,搜完整的也會搜出很多

query := elastic.NewMatchQuery("nick_name", "夜空中最亮的楓楓")
嵌套字段的搜索

ElementPlus UI

ElementUI 安裝及配置

一個 Vue 3 UI 框架 | Element Plus

安裝

npm install element-plus --save

按鈕

代碼

// demo\src\main.js
import { createApp } from 'vue'
?
//整體導入 ElementPlus 組件庫
import ElementPlus from 'element-plus' //導入 ElementPlus 組件庫的所有模塊和功能 
import 'element-plus/dist/index.css' //導入 ElementPlus 組件庫所需的全局 CSS 樣式
?
import App from './App.vue'
?
const app = createApp(App)
app.use(ElementPlus) //將 ElementPlus 插件注冊到 Vue 應用中
app.mount('#app')
<!--demo\src\App.vue-->
<script setup>
?
</script>
?
<template><h3>按鈕</h3><el-button>默認按鈕</el-button><el-button type="primary">主要按鈕</el-button><el-button type="success">成功按鈕</el-button><el-button type="info">信息按鈕</el-button><el-button type="warning">警告按鈕</el-button><el-button type="danger">危險按鈕</el-button>
?<hr><h3>按鈕屬性</h3><el-button plain>樸素按鈕</el-button><el-button round>圓角按鈕</el-button><el-button circle>圓</el-button><el-button disabled>禁用按鈕</el-button><el-button loading>加載中</el-button>
?<hr><h3>尺寸</h3><el-button size="large">大型按鈕</el-button><el-button>默認按鈕</el-button><el-button size="small">小型按鈕</el-button>
</template>s
?
<style scoped>
?
</style>

圖標

ElementPlus 圖標

Icon 圖標 | Element Plus

demo\src\main.jsimport { createApp } from 'vue'
?//整體導入 ElementPlus 組件庫import ElementPlus from 'element-plus' //導入 ElementPlus 組件庫的所有模塊和功能 import 'element-plus/dist/index.css' //導入 ElementPlus 組件庫所需的全局 CSS 樣式import * as ElementPlusIconsVue from '@element-plus/icons-vue' //導入 ElementPlus 組件庫中的所有圖標
?import App from './App.vue'
?const app = createApp(App)
?//注冊 ElementPlus 組件庫中的所有圖標到全局 Vue 應用中for (const [key, component] of Object.entries(ElementPlusIconsVue)) {app.component(key, component)}
?app.use(ElementPlus) //將 ElementPlus 插件注冊到 Vue 應用中app.mount('#app')
demo\src\App.vue
<script setup>
?
</script>
?
<template>
?
<h3>圖標</h3>
<el-icon><Plus /></el-icon>
<el-icon><Edit /></el-icon>
<el-icon><Delete /></el-icon>
<el-icon class="is-loading"><Loading /></el-icon>
?
<hr>
<h3>屬性</h3>
<el-icon size="30" color="red"><Search /></el-icon>
?
<hr>
<h3>按鈕</h3>
<el-button type="primary"><el-icon><Search /></el-icon><span> 搜索 </span></el-button>
?
<el-button type="primary"><el-icon><Search /></el-icon></el-button>
?
<el-button type="primary" circle><el-icon><Search /></el-icon></el-button>
?
<hr>
<h3>按鈕組</h3>
<el-button-group><el-button type="primary"><el-icon><Plus /></el-icon></el-button>
?<el-button type="primary"><el-icon><Edit /></el-icon></el-button>
?<el-button type="primary"><el-icon><Delete /></el-icon></el-button></el-button-group>
?
</template>
?
<style scoped>
?
</style>

提示框

demo\src\App.vue
<script setup>import { ElMessage, ElMessageBox, ElNotification } from 'element-plus'
?// 消息const openMsg = () => {ElMessage({type: 'success', // success | warning | info | errormessage: 'dengruicode.com',showClose: true})}
?// 確認框const openConfirm = () => {ElMessageBox.confirm('確認刪除?', '標題', {type: 'warning',confirmButtonText: '確認',cancelButtonText: '取消'}).then(() => {console.log('確認')}).catch(() => {console.log('取消')})}
?// 通知const openNotifiy = () => {ElNotification({title: '標題',message: '鄧瑞編程',duration: 1500 // 展示時間 [單位:毫秒]})}
?// 通知2const openNotifiy2 = () => {ElNotification({type: 'success', // success | warning | info | errortitle: '標題',message: 'dengruicode.com',duration: 1500,position: 'bottom-right'})}
</script>
?
<template>
<el-button @click="openMsg">消息</el-button>
<el-button @click="openConfirm">確認框</el-button>
<el-button @click="openNotifiy">通知</el-button>
<el-button @click="openNotifiy2">通知2</el-button>
</template>
?
<style scoped>
?
</style>

導航

demo\src\App.vue
<script setup>import { reactive, ref } from 'vue'
?//默認選中的菜單索引//const selectedIndex = ref("2-2")const selectedIndex = ref("3")
?//選中菜單觸發的回調const selected = (index, indexPath) => {console.log("index", index, "indexPath", indexPath)}
?//默認展開的菜單索引const defaultOpeneds = ref(["1","3"])
?//用戶執行的命令const userCommand = (command) => { //點擊菜單觸發的回調console.log("command:", command)}
</script>
?
<template>
?
<h3>水平導航</h3>
<el-menu mode="horizontal" :default-active="selectedIndex" @select="selected"><el-menu-item index="1">鄧瑞編程</el-menu-item><el-sub-menu index="2"><template #title>我的工作臺</template>
<el-menu-item index="2-1">選項1</el-menu-item>
<el-menu-item index="2-2">選項2</el-menu-item>
<el-menu-item index="2-3">選項3</el-menu-item>
</el-sub-menu>
<el-menu-item index="3">消息中心</el-menu-item>
<el-menu-item index="4">訂單管理</el-menu-item>
</el-menu>
?
?
<h3>水平導航-自定義樣式</h3>
<el-menu mode="horizontal" :default-active="selectedIndex" @select="selected" background-color="#545c64"text-color="#fff" active-text-color="#ffd04b" style="height: 40px; width: 600px;"><el-menu-item index="1">鄧瑞編程</el-menu-item><el-sub-menu index="2"><template #title>我的工作臺</template><el-menu-item index="2-1">選項1</el-menu-item><el-menu-item index="2-2">選項2</el-menu-item><el-menu-item index="2-3">選項3</el-menu-item></el-sub-menu><el-menu-item index="3">消息中心</el-menu-item><el-menu-item index="4">訂單管理</el-menu-item>
</el-menu>
?
<h3>垂直導航</h3><br>
<el-menu :default-active="selectedIndex" @select="selected" style="width: 200px;"><el-sub-menu index="1"><template #title>
<el-icon><Search /></el-icon>
<span>導航一</span></template><el-menu-item-group><el-menu-item index="1-1">選項1</el-menu-item><el-menu-item index="1-2">選項2</el-menu-item></el-menu-item-group></el-sub-menu><el-menu-item index="2"><el-icon><Edit /></el-icon><template #title>導航二</template></el-menu-item><el-menu-item index="3"><el-icon><Delete /></el-icon><template #title>導航三</template></el-menu-item><el-menu-item index="4"><el-icon><Setting /></el-icon><template #title>導航四</template></el-menu-item>
</el-menu>
?
<h3>垂直導航-默認展開和自定義樣式</h3>
<el-menu :default-active="selectedIndex" @select="selected" :default-openeds="defaultOpeneds"background-color="#545c64" text-color="#fff" active-text-color="#ffd04b" style="width: 200px;"><el-sub-menu index="1"><template #title>
<el-icon><Search /></el-icon>
<span>導航一</span></template><el-menu-item-group><el-menu-item index="1-1">選項1</el-menu-item><el-menu-item index="1-2">選項2</el-menu-item></el-menu-item-group></el-sub-menu><el-menu-item index="2"><el-icon><Edit /></el-icon><template #title>導航二</template></el-menu-item><el-sub-menu index="3"><template #title>
<el-icon><Search /></el-icon>
<span>導航三</span></template><el-menu-item-group><el-menu-item index="3-1">選項1</el-menu-item><el-menu-item index="3-2">選項2</el-menu-item></el-menu-item-group></el-sub-menu><el-menu-item index="4"><el-icon><Setting /></el-icon><template #title>導航四</template></el-menu-item>
</el-menu>
?
<h3>面包屑</h3>
<el-breadcrumb separator="/"><el-breadcrumb-item><a href="#">首頁</a></el-breadcrumb-item><el-breadcrumb-item>鄧瑞編程</el-breadcrumb-item><el-breadcrumb-item>dengruicode.com</el-breadcrumb-item>
</el-breadcrumb>
?
<h3>下拉菜單</h3><br>
<el-dropdown @command="userCommand"><span>個人中心<el-icon><User /></el-icon></span><template #dropdown>
<el-dropdown-menu><el-dropdown-item command="order">訂單</el-dropdown-item><el-dropdown-item command="logout">退出</el-dropdown-item></el-dropdown-menu></template>
</el-dropdown>
?
</template>
?
<style scoped>
?
</style>

標簽頁

demo\src\App.vue
<script setup>
?import { ref, reactive } from 'vue'
?//默認選中的標簽名稱const selectedName = ref("2")
?//選中標簽觸發的回調const tabClick = (tab, event) => {console.log("tab", tab.props, "event", event)}
?const tab = reactive({arr: [{ name: "1", title: '鄧瑞', content: '內容1' },{ name: "2", title: '鄧瑞編程', content: '內容2' },{ name: "3", title: 'dengruicode.com', content: '內容3' },]})
?//添加const tabAdd = () => {let index = tab.arr.lengthindex++
?tab.arr.push({name: index,title: '新選項卡' + index,content: '內容' + index})}
?//移除const tabRemove = (name) => {console.log("name:", name)
?const index = tab.arr.findIndex((value) => {return value.name === name})
?tab.arr.splice(index, 1) //移除元素}
?
</script>
?
<template>
?
<h3>標簽頁</h3>
<el-tabs v-model="selectedName" @tab-click="tabClick"><el-tab-pane label="鄧瑞" name="1">內容1</el-tab-pane><el-tab-pane label="鄧瑞編程" name="2">內容2</el-tab-pane><el-tab-pane label="dengruicode.com" name="3">內容3</el-tab-pane></el-tabs>
?
<h3>卡片風格</h3>
<el-tabs v-model="selectedName" @tab-click="tabClick" type="card"><el-tab-pane label="鄧瑞" name="a">內容1</el-tab-pane><el-tab-pane label="鄧瑞編程" name="b">內容2</el-tab-pane><el-tab-pane label="dengruicode.com" name="b">內容3</el-tab-pane></el-tabs>
?
<h3>帶有邊框的卡片風格</h3>
<el-tabs v-model="selectedName" @tab-click="tabClick" type="border-card"><el-tab-pane label="鄧瑞" name="A">內容1</el-tab-pane><el-tab-pane label="鄧瑞編程" name="B">內容2</el-tab-pane><el-tab-pane label="dengruicode.com" name="C">內容3</el-tab-pane></el-tabs>
?
<h3>動態添加</h3>
<el-button @click="tabAdd">添加</el-button>
?
<el-tabs v-model="selectedName" @tab-remove="tabRemove" closable type="card"><el-tab-pane v-for="(value, key) in tab.arr" :key="value.name" :label="value.title" :name="value.name">{{ value.content }}</el-tab-pane></el-tabs>
?
</template>
?
<style scoped>
?
</style>

輸入框

demo\src\App.vue
<script setup>import { ref } from 'vue'const name = ref('')const password = ref('')const content = ref('鄧瑞編程')const url = ref('dengruicode.com')const url2 = ref('dengruicode')const email = ref('123456')//const selected = ref('')const selected = ref('2') //選中的下拉框
</script><template>
<div style="width: 300px;"><!-- clearable 可一鍵清空 --><h3>輸入框</h3><el-input v-model="name" clearable placeholder="請輸入用戶名" /><!-- show-password 可切換顯示隱藏密碼 --><h3>密碼框</h3><el-input v-model="password" show-password placeholder="請輸入密碼" /><h3>文本域</h3><el-input type="textarea" v-model="content" rows="2" /><h3>輸入內容長度限制 - 輸入框</h3><el-input v-model="name" maxlength="10" show-word-limit /><h3>輸入內容長度限制 - 文本域</h3><el-input type="textarea" v-model="content" maxlength="20" rows="3" show-word-limit /><h3>尺寸</h3>大 <el-input size="large" />默認 <el-input />小 <el-input size="small" /><h3>前置</h3><el-input v-model="url"><template #prepend>https://</template>
</el-input><h3>后置</h3>
<el-input v-model="email"><template #append>@qq.com</template>
</el-input><h3>前置后置</h3>
<el-input v-model="url2"><template #prepend>https://</template><template #append>.com</template>
</el-input><h3>前置后置擴展 - 搜索</h3>
<el-input placeholder="請輸入課程名稱"><template #prepend>
<el-select v-model="selected" placeholder="請選擇" style="width: 100px;"><el-option label="前端" value="1" /><el-option label="后端" value="2" /><el-option label="服務端" value="3" /></el-select></template><template #append>
<el-button><el-icon><Search /></el-icon></el-button></template>
</el-input>
</div>
</template><style scoped></style>

單選框、復選框

demo\src\App.vue
<script setup>import { ref } from 'vue'//單選框const radio = ref("3")const radio2 = ref("b")const radio3 = ref("C")const radioChange = (val) => {console.log("radioChange:", val)}const radioGroupChange = (val) => {console.log("radioGroupChange:", val)}//復選框const checked = ref(["1", "2"])const checked2 = ref([])const checkboxGroupChange = (val) => {console.log("checkboxGroupChange", val)}
</script><template>
<h3>單選框</h3>
<el-radio v-model="radio" value="1">前端</el-radio>
<el-radio v-model="radio" value="2">后端</el-radio>
<el-radio v-model="radio" value="3">服務端</el-radio><h3>單選框 - 事件綁定</h3>
<el-radio v-model="radio2" value="a" @change="radioChange">前端</el-radio>
<el-radio v-model="radio2" value="b" @change="radioChange">后端</el-radio>
<el-radio v-model="radio2" value="c" @change="radioChange">服務端</el-radio><h3>單選框組</h3>
<el-radio-group v-model="radio3" @change="radioGroupChange"><el-radio value="A">前端</el-radio><el-radio value="B">后端</el-radio><el-radio value="C">服務端</el-radio></el-radio-group><h3>復選框</h3>
<el-checkbox-group v-model="checked"><el-checkbox value="1">前端</el-checkbox><el-checkbox value="2">后端</el-checkbox><el-checkbox value="3">服務端</el-checkbox></el-checkbox-group><h3>事件綁定</h3>
<el-checkbox-group v-model="checked2" @change="checkboxGroupChange"><el-checkbox value="1">前端</el-checkbox><el-checkbox value="2">后端</el-checkbox><el-checkbox value="3">服務端</el-checkbox></el-checkbox-group>
</template><style scoped></style>

下拉框

demo\src\App.vue
<script setup>import { ref,reactive } from 'vue'const selected = ref('2')const selected2 = ref('')const selected3 = ref('C')const selected4 = ref(['1','3'])const data = reactive({options: [{ value: 'A', label: '前端', },{ value: 'B', label: '后端', },{ value: 'C', label: '服務端', }]})//回調const selectChange = (val) => {console.log("selectChange:", val)}
</script><template>
<div style="width: 300px;"><h3>下拉框</h3><el-select v-model="selected" placeholder="請選擇"><el-option value="1" label="前端" /><el-option value="2" label="后端" /><el-option value="3" label="服務端" /></el-select><h3>下拉框 - 事件綁定</h3><el-select v-model="selected2" @change="selectChange" placeholder="請選擇"><el-option value="a" label="前端" /><el-option value="b" label="后端" /><el-option value="c" label="服務端" /></el-select><h3>動態下拉框</h3><el-select v-model="selected3" placeholder="請選擇"><el-option v-for="item in data.options" :value="item.value" :label="item.label":key="item.value" /></el-select><h3>多選 - multiple</h3><el-select v-model="selected4" multiple @change="selectChange" placeholder="請選擇"><el-option value="1" label="前端" /><el-option value="2" label="后端" /><el-option value="3" label="服務端" /></el-select></div>
</template><style scoped></style>

日期選擇器

demo\src\main.jsimport { createApp } from 'vue'//整體導入 ElementPlus 組件庫import ElementPlus from 'element-plus' //導入 ElementPlus 組件庫的所有模塊和功能 import 'element-plus/dist/index.css' //導入 ElementPlus 組件庫所需的全局 CSS 樣式import * as ElementPlusIconsVue from '@element-plus/icons-vue' //導入 ElementPlus 組件庫中的所有圖標import zhCn from 'element-plus/dist/locale/zh-cn.mjs' //導入 ElementPlus 組件庫的中文語言包import App from './App.vue'const app = createApp(App)//注冊 ElementPlus 組件庫中的所有圖標到全局 Vue 應用中for (const [key, component] of Object.entries(ElementPlusIconsVue)) {app.component(key, component)}//app.use(ElementPlus) //將 ElementPlus 插件注冊到 Vue 應用中sapp.use(ElementPlus, {locale: zhCn // 設置 ElementPlus 組件庫的區域語言為中文簡體})app.mount('#app')
demo\src\App.vue
<script setup>import { ref } from 'vue'const date = ref('')const dateChange = (val) => {console.log("dateChange:", val)}
</script><template>
<h3>日期</h3>
<el-date-picker v-model="date" type="date" placeholder="請選擇" /><h3>日期時間</h3>
<el-date-picker v-model="date" type="datetime" placeholder="請選擇" /><h3>事件綁定</h3>
<el-date-picker v-model="date" type="datetime" value-format="YYYY-MM-DD HH:mm:ss" @change="dateChange" />
</template><style scoped></style>

表單

demo\src\App.vue
<script setup>import { ref } from 'vue'const data = ref({name: '',radio: '',checkbox: [],date: '',select: '',multipleSelect: [],textarea: ''})const add = () => {console.log(data.value)}const reset = () => {data.value = {name: '',radio: '',checkbox: [],date: '',select: '',multipleSelect: [],textarea: ''}}
</script><template>
<el-form label-width="80" style="width: 400px;"><el-form-item label="文本框"><el-input v-model="data.name" placeholder="請填寫名稱" /></el-form-item><el-form-item label="單選框"><el-radio-group v-model="data.radio"><el-radio value="1">前端</el-radio><el-radio value="2">后端</el-radio><el-radio value="3">服務端</el-radio></el-radio-group></el-form-item><el-form-item label="復選框"><el-checkbox-group v-model="data.checkbox"><el-checkbox value="a">前端</el-checkbox><el-checkbox value="b">后端</el-checkbox><el-checkbox value="c">服務端</el-checkbox></el-checkbox-group></el-form-item><el-form-item label="日期時間"><el-date-picker v-model="data.date" type="datetime" value-format="YYYY-MM-DD HH:mm:ss" /></el-form-item><el-form-item label="下拉框"><el-select v-model="data.select" placeholder="請選擇"><el-option value="A" label="前端" /><el-option value="B" label="后端" /><el-option value="C" label="服務端" /></el-select></el-form-item><el-form-item label="多選框"><el-select v-model="data.multipleSelect" multiple placeholder="請選擇"><el-option value="AA" label="前端" /><el-option value="BB" label="后端" /><el-option value="CC" label="服務端" /></el-select></el-form-item><el-form-item label="文本域"><el-input type="textarea" v-model="data.textarea" rows="2" placeholder="請填寫內容" /></el-form-item><el-form-item><el-button type="primary" @click="add">添加</el-button><el-button @click="reset">重置</el-button></el-form-item></el-form>
</template><style scoped></style>

對話框

demo\src\App.vue
<script setup>import { ref } from 'vue'const data = ref({name: '',radio: '',checkbox: [],date: '',select: '',multipleSelect: [],textarea: ''})const add = () => {console.log(data.value)}const reset = () => {data.value = {name: '',radio: '',checkbox: [],date: '',select: '',multipleSelect: [],textarea: ''}}//對話框const dialog = ref(false)const dialogClose = () => {console.log("關閉")}
</script><template>
<el-button @click="dialog = true">打開</el-button><!-- draggable 允許拖拽 -->
<el-dialog v-model="dialog" width="500" title="標題" draggable @close="dialogClose"><el-form label-width="80"><el-form-item label="文本框"><el-input v-model="data.name" placeholder="請填寫名稱" /></el-form-item><el-form-item label="單選框"><el-radio-group v-model="data.radio"><el-radio value="1">前端</el-radio><el-radio value="2">后端</el-radio><el-radio value="3">服務端</el-radio></el-radio-group></el-form-item><el-form-item label="復選框"><el-checkbox-group v-model="data.checkbox"><el-checkbox value="a">前端</el-checkbox><el-checkbox value="b">后端</el-checkbox><el-checkbox value="c">服務端</el-checkbox></el-checkbox-group></el-form-item><el-form-item label="日期時間"><el-date-picker v-model="data.date" type="datetime" value-format="YYYY-MM-DD HH:mm:ss" /></el-form-item><el-form-item label="下拉框"><el-select v-model="data.select" placeholder="請選擇"><el-option value="A" label="前端" /><el-option value="B" label="后端" /><el-option value="C" label="服務端" /></el-select></el-form-item><el-form-item label="多選框"><el-select v-model="data.multipleSelect" multiple placeholder="請選擇"><el-option value="AA" label="前端" /><el-option value="BB" label="后端" /><el-option value="CC" label="服務端" /></el-select></el-form-item><el-form-item label="文本域"><el-input type="textarea" v-model="data.textarea" rows="2" placeholder="請填寫內容" /></el-form-item><el-form-item><el-button type="primary" @click="add">添加</el-button><el-button @click="reset">重置</el-button></el-form-item></el-form></el-dialog>
</template><style scoped></style>

分頁

demo\src\App.vue
<script setup>const currentPage = (val) => {console.log("currentPage:",val)}
</script><template>
<h3>page-size:每頁顯示記錄數 total:總記錄數</h3>
<el-pagination layout="prev, pager, next" :page-size="10" :total="50" /><h3>background:顯示背景</h3>
<el-pagination layout="prev, pager, next" :page-size="5" :total="50" background /><h3>layout="total" 顯示總數</h3>
<el-pagination layout="prev, pager, next, total" :page-size="5" :total="50" /><h3>layout="jumper" 跳轉</h3>
<el-pagination layout="prev, pager, next, jumper, total" :page-size="5" :total="50" /><h3>事件綁定</h3>
<el-pagination layout="prev, pager, next" :page-size="5" :total="50" @current-change="currentPage" />
</template><style scoped></style>

表格

demo\src\App.vue
<script setup>import { ref } from 'vue'const data = ref({arr: [{ id: '1', name: '鄧瑞', web: 'dengruicode.com', date: '2023-06-20' },{ id: '2', name: 'David', web: 'www.dengruicode.com', date: '2023-06-21' },{ id: '3', name: 'Luna', web: 'dengruicode.com', date: '2023-06-22' },{ id: '4', name: 'Lisa', web: 'www.dengruicode.com', date: '2023-06-22' }]})//選中的復選框let idArr = []const selected = (data) => {//console.log("selected", data)idArr = [] //重置data.forEach((value) => {idArr.push(value.id)})console.log("idArr:", idArr)}//刪除const del = () => {console.log("del:", idArr)}//編輯const edit = (index, row) => {console.log("index:", index, "row:", row)}    
</script><template>
<h3>表格</h3>
<el-table :data="data.arr" style="width: 800px;"><el-table-column prop="id" label="編號" width="80" /><el-table-column prop="name" label="姓名" /><el-table-column prop="web" label="網站" width="300" /><el-table-column prop="date" label="日期" /></el-table><h3>帶邊框表格</h3>
<el-table :data="data.arr" border style="width: 800px;"><el-table-column prop="id" label="編號" width="80" /><el-table-column prop="name" label="姓名" /><el-table-column prop="web" label="網站" width="300" /><el-table-column prop="date" label="日期" /></el-table><h3>設置高度固定表頭</h3>
<el-table :data="data.arr" border height="120" style="width: 800px;"><el-table-column prop="id" label="編號" width="80" /><el-table-column prop="name" label="姓名" /><el-table-column prop="web" label="網站" width="300" /><el-table-column prop="date" label="日期" /></el-table><h3>type="selection" 多選</h3>
<el-table :data="data.arr" border style="width: 800px;"><el-table-column type="selection" width="55" /><el-table-column prop="id" label="編號" width="80" /><el-table-column prop="name" label="姓名" /><el-table-column prop="web" label="網站" width="300" /><el-table-column prop="date" label="日期" /></el-table><h3>按鈕</h3>
<el-button type="primary" @click="del">刪除</el-button><el-table :data="data.arr" @selection-change="selected" border style="width: 900px;margin: 3px 0;"><el-table-column type="selection" width="55"></el-table-column><el-table-column prop="id" label="編號" width="80" /><el-table-column prop="name" label="姓名" /><el-table-column prop="web" label="網站" width="300" /><el-table-column prop="date" label="日期" /><el-table-column label="操作" width="150"><template #default="scope"><el-button size="small" type="primary" @click="edit(scope.$index, scope.row)">編輯</el-button><el-button size="small">刪除</el-button>
</template>
</el-table-column>
</el-table><el-pagination layout="prev, pager, next, jumper, total" :page-size="5" :total="50" />
</template><style scoped></style>

按需導入

代碼#自動導入#安裝 unplugin-vue-components 和 unplugin-auto-import 插件npm install -D unplugin-vue-components unplugin-auto-import#自動導入 圖標#安裝 unplugin-icons 插件npm install -D unplugin-icons代碼demo\vite.config.jsimport { defineConfig } from 'vite'import vue from '@vitejs/plugin-vue'//unpluginimport AutoImport from 'unplugin-auto-import/vite'import Components from 'unplugin-vue-components/vite'import { ElementPlusResolver } from 'unplugin-vue-components/resolvers'import Icons from 'unplugin-icons/vite' //圖標import IconsResolver from 'unplugin-icons/resolver'// https://vitejs.dev/config/export default defineConfig({plugins: [vue(),AutoImport({// 自動導入 Vue 相關函數,如:ref, reactive, toRef 等imports: ['vue'], resolvers: [ElementPlusResolver(),// 自動導入圖標組件IconsResolver(),],}),Components({resolvers: [ElementPlusResolver(),// 自動注冊圖標組件IconsResolver({enabledCollections: ['ep'],}),],}),Icons({autoInstall: true,}),],})demo\src\main.jsimport { createApp } from 'vue'/*//整體導入 ElementPlus 組件庫import ElementPlus from 'element-plus' //導入 ElementPlus 組件庫的所有模塊和功能 import 'element-plus/dist/index.css' //導入 ElementPlus 組件庫所需的全局 CSS 樣式import * as ElementPlusIconsVue from '@element-plus/icons-vue' //導入 ElementPlus 組件庫中的所有圖標import zhCn from 'element-plus/dist/locale/zh-cn.mjs' //導入 ElementPlus 組件庫的中文語言包*/import App from './App.vue'const app = createApp(App)/*//注冊 ElementPlus 組件庫中的所有圖標到全局 Vue 應用中for (const [key, component] of Object.entries(ElementPlusIconsVue)) {app.component(key, component)}//app.use(ElementPlus) //將 ElementPlus 插件注冊到 Vue 應用中sapp.use(ElementPlus, {locale: zhCn // 設置 ElementPlus 組件庫的區域語言為中文簡體})*/app.mount('#app')demo\src\App.vue<script setup>// 消息const openMsg = () => {ElMessage({type: 'success', // success | warning | info | errormessage: 'dengruicode.com',showClose: true})}// 確認框const openConfirm = () => {ElMessageBox.confirm('確認刪除?', '標題', {type: 'warning',confirmButtonText: '確認',cancelButtonText: '取消'}).then(() => {console.log('確認')}).catch(() => {console.log('取消')})}// 通知const openNotifiy = () => {ElNotification({title: '標題',message: '鄧瑞編程',duration: 1500 // 展示時間 [單位:毫秒]})}// 通知2const openNotifiy2 = () => {ElNotification({type: 'success', // success | warning | info | errortitle: '標題',message: 'dengruicode.com',duration: 1500,position: 'bottom-right'})}const url = ref('dengruicode.com')</script><template><h3>按鈕</h3><el-button>默認按鈕</el-button><el-button type="primary">主要按鈕</el-button><el-button type="success">成功按鈕</el-button><el-button type="info">信息按鈕</el-button><el-button type="warning">警告按鈕</el-button><el-button type="danger">危險按鈕</el-button><h3>圖標</h3><!-- <el-icon><Plus /></el-icon> --><el-icon><i-ep-Plus /></el-icon> <!-- i-ep- --><el-icon><IEpEdit /></el-icon> <!-- IEp- --><el-icon><IEpDelete /></el-icon><el-icon class="is-loading"><IEpLoading /></el-icon><h3>提示框</h3><el-button @click="openMsg">消息</el-button><el-button @click="openConfirm">確認框</el-button><el-button @click="openNotifiy">通知</el-button><el-button @click="openNotifiy2">通知2</el-button><h3>輸入框</h3><el-input v-model="url" placeholder="請輸入網址" /></template><style scoped></style>

ECharts 安裝

獨立版本(推薦下載本地)

cdn.staticfile.net/echarts/4.7.0/echarts.min.js

cdn.staticfile.net/echarts/4.7.0/echarts.js

使用 CDN 方法

  • Staticfile CDN(國內) : https://cdn.staticfile.net/echarts/4.3.0/echarts.min.js

  • jsDelivr:https://cdn.jsdelivr.net/npm/echarts@4.3.0/dist/echarts.min.js。

  • cdnjs : https://cdnjs.cloudflare.com/ajax/libs/echarts/4.3.0/echarts.min.js

<script src="https://cdn.staticfile.net/echarts/4.3.0/echarts.min.js"></script>

ECharts 實例

<!DOCTYPE html>
<html><head><meta charset="utf-8"><title>第一個 ECharts 實例</title><!-- 引入 echarts.js --><script src="https://cdn.staticfile.org/echarts/4.3.0/echarts.min.js"></script></head><body><!-- 為ECharts準備一個具備大小(寬高)的Dom --><div id="main" style="width: 600px;height:400px;"></div><script type="text/javascript">// 基于準備好的dom,初始化echarts實例var myChart = echarts.init(document.getElementById('main'));
?// 指定圖表的配置項和數據var option = {title: {text: '第一個 ECharts 實例'},tooltip: {}, ?// 提示信息legend: {data:['銷量']}, ?// 圖例主鍵xAxis: {data: ["襯衫","羊毛衫","雪紡衫","褲子","高跟鞋","襪子"]},yAxis: {},// 系列列表series: [{name: '銷量',type: 'bar',data: [5, 20, 36, 10, 10, 20]}]};// 使用剛指定的配置項和數據顯示圖表myChart.setOption(option);</script></body>
</html>
<script>// 圖例組件legend: {data: [{name: '系列1',// 強制設置圖形為圓。icon: 'circle',// 設置文本為紅色textStyle: {color: 'red'}}]}
</script>

ECharts圖表類型

<!-- 圖表類型 -->
type: 'bar':柱狀/條形圖
type: 'line':折線/面積圖
type: 'pie':餅圖
type: 'scatter':散點(氣泡)圖
type: 'effectScatter':帶有漣漪特效動畫的散點(氣泡)
type: 'radar':雷達圖
type: 'tree':樹型圖
type: 'treemap':樹型圖
type: 'sunburst':旭日圖
type: 'boxplot':箱形圖
type: 'candlestick':K線圖
type: 'heatmap':熱力圖
type: 'map':地圖
type: 'parallel':平行坐標系的系列
type: 'lines':線圖
type: 'graph':關系圖
type: 'sankey':桑基圖
type: 'funnel':漏斗圖
type: 'gauge':儀表盤
type: 'pictorialBar':象形柱圖
type: 'themeRiver':主題河流
type: 'custom':自定義系列

ECharts 餅圖

<!-- 引入 echarts.js -->
<script src="https://cdn.staticfile.net/echarts/4.3.0/echarts.min.js"></script>
</head>
<body><!-- 為ECharts準備一個具備大小(寬高)的Dom --><div id="main" style="width: 600px;height:400px;"></div><script type="text/javascript">// 基于準備好的dom,初始化echarts實例var myChart = echarts.init(document.getElementById('main'));myChart.setOption({series : [{name: '訪問來源',type: 'pie',    // 設置圖表類型為餅圖radius: '55%',  // 餅圖的半徑,外半徑為可視區尺寸(容器高寬中較小一項)的 55% 長度。data:[          // 數據數組,name 為數據項名稱,value 為數據項值{value:235, name:'視頻廣告'},{value:274, name:'聯盟廣告'},{value:310, name:'郵件營銷'},{value:335, name:'直接訪問'},{value:400, name:'搜索引擎'}]}]})</script>
</body>

南丁格爾圖

<!-- roseType: 'angle', 餅圖顯示成南丁格爾圖 -->
<script src="https://cdn.staticfile.net/echarts/4.3.0/echarts.min.js"></script>
</head>
<body><!-- 為ECharts準備一個具備大小(寬高)的Dom --><div id="main" style="width: 600px;height:400px;"></div><script type="text/javascript">// 基于準備好的dom,初始化echarts實例var myChart = echarts.init(document.getElementById('main'));// 指定圖表的配置項和數據var option = {series : [{name: '訪問來源',type: 'pie',radius: '55%',roseType: 'angle',    // 餅圖顯示成南丁格爾圖data:[{value:235, name:'視頻廣告'},{value:274, name:'聯盟廣告'},{value:310, name:'郵件營銷'},{value:335, name:'直接訪問'},{value:400, name:'搜索引擎'}]}]};// 使用剛指定的配置項和數據顯示圖表。myChart.setOption(option);</script>

陰影的配置

<!-- 引入 echarts.js -->
<script src="https://cdn.staticfile.net/echarts/4.3.0/echarts.min.js"></script>
</head>
<body><!-- 為ECharts準備一個具備大小(寬高)的Dom --><div id="main" style="width: 600px;height:400px;"></div><script type="text/javascript">// 基于準備好的dom,初始化echarts實例var myChart = echarts.init(document.getElementById('main'));// 指定圖表的配置項和數據var option = {series : [{name: '訪問來源',type: 'pie',radius: '55%',data:[{value:235, name:'視頻廣告'},{value:274, name:'聯盟廣告'},{value:310, name:'郵件營銷'},{value:335, name:'直接訪問'},{value:400, name:'搜索引擎'}],roseType: 'angle',itemStyle: {normal: {shadowBlur: 200,shadowColor: 'rgba(0, 0, 0, 0.5)'}}}]};// 使用剛指定的配置項和數據顯示圖表myChart.setOption(option);</script>
</body>

ECharts 樣式設置

顏色主題

ECharts4 開始,除了默認主題外,內置了兩套主題,分別為 lightdark

<!-- 使用方式 -->
var chart = echarts.init(dom, 'light');
var chart = echarts.init(dom, 'dark');
<script src="https://cdn.staticfile.net/echarts/4.3.0/echarts.min.js"></script>
</head>
<body><!-- 為ECharts準備一個具備大小(寬高)的Dom --><div id="main" style="width: 600px;height:400px;"></div><script type="text/javascript">// 基于準備好的dom,初始化echarts實例var myChart = echarts.init(document.getElementById('main'), 'dark'); // dark 可嘗試修改為 lightmyChart.setOption({series : [{name: '訪問來源',type: 'pie',    // 設置圖表類型為餅圖radius: '55%',  // 餅圖的半徑,外半徑為可視區尺寸(容器高寬中較小一項)的 55% 長度。data:[          // 數據數組,name 為數據項名稱,value 為數據項值{value:235, name:'視頻廣告'},{value:274, name:'聯盟廣告'},{value:310, name:'郵件營銷'},{value:335, name:'直接訪問'},{value:400, name:'搜索引擎'}]}]})</script>
</body>

另外,我們也可以在官方的 主題編輯器 選擇自己喜歡的主題下載

<!-- 下載并引入主題 -->
<script src="https://www.runoob.com/static/js/wonderland.js"></script>
var myChart = echarts.init(dom, 'wonderland');
$.getJSON('wonderland.json', function (themeJSON) {echarts.registerTheme('wonderland', themeJSON)var myChart = echarts.init(dom, 'wonderland');
});

調色盤

// 全局調色盤。
color: ['#ff0000','#00ff00', '#0000ff', '#d48265', '#91c7ae','#749f83',  '#ca8622', '#bda29a','#6e7074', '#546570', '#c4ccd3'],
<!-- 引入 echarts.js -->
<script src="https://cdn.staticfile.net/echarts/4.3.0/echarts.min.js"></script>
</head>
<body><!-- 為ECharts準備一個具備大小(寬高)的Dom --><div id="main" style="width: 600px;height:400px;"></div><script type="text/javascript">// 基于準備好的dom,初始化echarts實例svar myChart = echarts.init(document.getElementById('main'));myChart.setOption({// 全局調色盤color: ['#ff0000','#00ff00', '#0000ff', '#d48265', '#91c7ae','#749f83',  '#ca8622', '#bda29a','#6e7074', '#546570', '#c4ccd3'],series : [{name: '訪問來源',type: 'pie',    // 設置圖表類型為餅圖radius: '55%',  // 餅圖的半徑,外半徑為可視區尺寸(容器高寬中較小一項)的 55% 長度。data:[          // 數據數組,name 為數據項名稱,value 為數據項值{value:235, name:'視頻廣告'},{value:274, name:'聯盟廣告'},{value:310, name:'郵件營銷'},{value:335, name:'直接訪問'},{value:400, name:'搜索引擎'}]}]})</script>

直接的樣式設置 itemStyle, lineStyle, areaStyle, label, ...

高亮的樣式:emphasis

<!-- 引入 echarts.js -->
<script src="https://cdn.staticfile.net/echarts/4.3.0/echarts.min.js"></script>
</head>
<body><!-- 為ECharts準備一個具備大小(寬高)的Dom --><div id="main" style="width: 600px;height:400px;"></div><script type="text/javascript">// 基于準備好的dom,初始化echarts實例var myChart = echarts.init(document.getElementById('main'));myChart.setOption({series : [{name: '訪問來源',type: 'pie',    // 設置圖表類型為餅圖radius: '55%',  // 餅圖的半徑,外半徑為可視區尺寸(容器高寬中較小一項)的 55% 長度。// 高亮樣式。emphasis: {itemStyle: {// 高亮時點的顏色color: 'red'},label: {show: true,// 高亮時標簽的文字formatter: '高亮時顯示的標簽內容'}},data:[          // 數據數組,name 為數據項名稱,value 為數據項值{value:235, name:'視頻廣告'},{value:274, name:'聯盟廣告'},{value:310, name:'郵件營銷'},{value:335, name:'直接訪問'},{value:400, name:'搜索引擎'}]}]})</script>
</body>

ECharts 異步加載數據

// echarts_test_data.json 數據:
{	"data_pie" : [{"value":235, "name":"視頻廣告"},{"value":274, "name":"聯盟廣告"},{"value":310, "name":"郵件營銷"},{"value":335, "name":"直接訪問"},{"value":400, "name":"搜索引擎"}]
}
<script src="https://cdn.staticfile.net/jquery/2.2.4/jquery.min.js"></script>
<!-- 引入 echarts.js -->
<script src="https://cdn.staticfile.net/echarts/4.3.0/echarts.min.js"></script>
</head>
<body><!-- 為ECharts準備一個具備大小(寬高)的Dom --><div id="main" style="width: 600px;height:400px;"></div><script type="text/javascript">// 基于準備好的dom,初始化echarts實例var myChart = echarts.init(document.getElementById('main'));myChart.showLoading();  // 開啟 loading 效果$.get('https://www.runoob.com/static/js/echarts_test_data.json', function (data) {alert("可以看到 loading 字樣"); // 測試代碼,用于查看 loading 效果myChart.hideLoading();  // 隱藏 loading 效果myChart.setOption({sseries : [{name: '訪問來源',type: 'pie',    // 設置圖表類型為餅圖radius: '55%',  // 餅圖的半徑,外半徑為可視區尺寸(容器高寬中較小一項)的 55% 長度。data:data.data_pie}]})}, 'json');</script>

數據的動態更新

<script src="https://cdn.staticfile.net/jquery/2.2.4/jquery.min.js"></script>
<!-- 引入 echarts.js -->
<script src="https://cdn.staticfile.net/echarts/4.3.0/echarts.min.js"></script>
</head>
<body><!-- 為ECharts準備一個具備大小(寬高)的Dom --><div id="main" style="width: 600px;height:400px;"></div><script type="text/javascript">var base = +new Date(2014, 9, 3);    // 定義了一個變量base,它是一個時間戳,表示2014年10月3日的日期var oneDay = 24 * 3600 * 1000;    // 定義了一個變量oneDay,用來表示一天的毫秒數var date = [];    //  定義了一個空數組date,用來存儲日期數據var data = [Math.random() * 150];    // 定義了一個數組data,初始化為包含一個隨機數乘以150的結果var now = new Date(base);    // 定義了一個變量now,初始化為base時間戳對應的日期對象function addData(shift) {    // 定義了一個函數addData,它用于添加新的數據點到圖表中。參數shift決定是否移除舊的數據點now = [now.getFullYear(), now.getMonth() + 1, now.getDate()].join('/');    // 這行代碼獲取當前日期對象的年、月、日,并將其格式化為字符串date.push(now);    // 將格式化后的日期字符串添加到date數組data.push((Math.random() - 0.4) * 10 + data[data.length - 1]);    // 這行代碼生成一個新的隨機數據點,并將其添加到data數組if (shift) { date.shift();data.shift();}now = new Date(+new Date(now) + oneDay);    // 更新now變量為當前日期的下一天}for (var i = 1; i < 100; i++) {addData();}option = {xAxis: {type: 'category',	// type: 'category'表示x軸是分類軸boundaryGap: false,data: date},yAxis: {boundaryGap: [0, '50%'],type: 'value'},series: [{name:'成交',type:'line',	// 設置數據系列的類型為折線圖smooth:true,    // 設置折線圖是否平滑symbol: 'none',	// 設置折線圖的數據點是否顯示標記,這里設置為不顯示stack: 'a',		// 設置數據系列的堆疊方式,這里設置為堆疊到'a'areaStyle: {// 設置折線圖的區域樣式,這里沒有具體設置樣式屬性normal: {}},data: data}]};setInterval(function () {addData(true);		// 在定時器的回調函數中調用addData函數,并傳遞true作為參數,表示每次更新時都移除最舊的數據點myChart.setOption({    //  使用setOption方法更新圖表的配置選項xAxis: {data: date},series: [{name:'成交',data: data}]});}, 500);    // 設置一個定時器,每500毫秒調用一次函數,更新圖表數據// 基于準備好的dom,初始化echarts實例var myChart = echarts.init(document.getElementById('main'));myChart.setOption(option)</script>

ECharts 數據集(dataset)

<script src="https://cdn.staticfile.net/echarts/4.3.0/echarts.min.js"></script>
</head>
<body><!-- 為ECharts準備一個具備大小(寬高)的Dom --><div id="main" style="width: 600px;height:400px;"></div><script type="text/javascript">// 基于準備好的dom,初始化echarts實例var myChart = echarts.init(document.getElementById('main'));// 指定圖表的配置項和數據var option = {legend: {},tooltip: {},dataset: {// 提供一份數據。source: [['product', '2015', '2016', '2017'],['Matcha Latte', 43.3, 85.8, 93.7],['Milk Tea', 83.1, 73.4, 55.1],['Cheese Cocoa', 86.4, 65.2, 82.5],['Walnut Brownie', 72.4, 53.9, 39.1]]},// 聲明一個 X 軸,類目軸(category)。默認情況下,類目軸對應到 dataset 第一列。xAxis: {type: 'category'},// 聲明一個 Y 軸,數值軸。yAxis: {},// 聲明多個 bar 系列,默認情況下,每個系列會自動對應到 dataset 的每一列。series: [{type: 'bar'},{type: 'bar'},{type: 'bar'}]};// 使用剛指定的配置項和數據顯示圖表。myChart.setOption(option);</script>
</body>
<script src="https://cdn.staticfile.net/echarts/4.3.0/echarts.min.js"></script>
</head>
<body><!-- 為ECharts準備一個具備大小(寬高)的Dom --><div id="main" style="width: 600px;height:400px;"></div><script type="text/javascript">// 基于準備好的dom,初始化echarts實例var myChart = echarts.init(document.getElementById('main'));// 指定圖表的配置項和數據var option = {legend: {},tooltip: {},dataset: {// 這里指定了維度名的順序,從而可以利用默認的維度到坐標軸的映射。// 如果不指定 dimensions,也可以通過指定 series.encode 完成映射,參見后文。dimensions: ['product', '2015', '2016', '2017'],source: [{product: 'Matcha Latte', '2015': 43.3, '2016': 85.8, '2017': 93.7},{product: 'Milk Tea', '2015': 83.1, '2016': 73.4, '2017': 55.1},{product: 'Cheese Cocoa', '2015': 86.4, '2016': 65.2, '2017': 82.5},{product: 'Walnut Brownie', '2015': 72.4, '2016': 53.9, '2017': 39.1}]},xAxis: {type: 'category'},yAxis: {},series: [{type: 'bar'},{type: 'bar'},{type: 'bar'}]};// 使用剛指定的配置項和數據顯示圖表。myChart.setOption(option);</script>
</body>

數據到圖形的映射

<script src="https://cdn.staticfile.net/echarts/4.3.0/echarts.min.js"></script>
</head>
<body><div id="main" style="width: 600px;height:400px;"></div><script type="text/javascript">var myChart = echarts.init(document.getElementById('main'));var option = {legend: {},tooltip: {},dataset: {source: [['product', '2012', '2013', '2014', '2015'],['Matcha Latte', 41.1, 30.4, 65.1, 53.3],['Milk Tea', 86.5, 92.1, 85.7, 83.1],['Cheese Cocoa', 24.1, 67.2, 79.5, 86.4]]},xAxis: [{type: 'category', gridIndex: 0},{type: 'category', gridIndex: 1}],yAxis: [{gridIndex: 0},{gridIndex: 1}],grid: [{bottom: '55%'},{top: '55%'}],series: [// 這幾個系列會在第一個直角坐標系中,每個系列對應到 dataset 的每一行{type: 'bar', seriesLayoutBy: 'row'},{type: 'bar', seriesLayoutBy: 'row'},{type: 'bar', seriesLayoutBy: 'row'},// 這幾個系列會在第二個直角坐標系中,每個系列對應到 dataset 的每一列{type: 'bar', xAxisIndex: 1, yAxisIndex: 1},{type: 'bar', xAxisIndex: 1, yAxisIndex: 1},{type: 'bar', xAxisIndex: 1, yAxisIndex: 1},{type: 'bar', xAxisIndex: 1, yAxisIndex: 1}]}// 使用剛指定的配置項和數據顯示圖表。myChart.setOption(option);</script>
</body>

豎表

eries.encode 屬性將對應的數據映射到坐標軸(如 X、Y 軸)

<script src="https://cdn.staticfile.net/echarts/4.3.0/echarts.min.js"></script>
</head>
<body><div id="main" style="width: 600px;height:400px;"></div><script type="text/javascript">var myChart = echarts.init(document.getElementById('main'));var option = {dataset: {source: [['score', 'amount', 'product'],[89.3, 58212, 'Matcha Latte'],[57.1, 78254, 'Milk Tea'],[74.4, 41032, 'Cheese Cocoa'],[50.1, 12755, 'Cheese Brownie'],[89.7, 20145, 'Matcha Cocoa'],[68.1, 79146, 'Tea'],[19.6, 91852, 'Orange Juice'],[10.6, 101852, 'Lemon Juice'],[32.7, 20112, 'Walnut Brownie']]},grid: {containLabel: true},xAxis: {},yAxis: {type: 'category'},series: [{type: 'bar',encode: {// 將 "amount" 列映射到 X 軸。x: 'amount',// 將 "product" 列映射到 Y 軸。y: 'product'}}]};// 使用剛指定的配置項和數據顯示圖表。myChart.setOption(option);</script>
</body>

更多 encode 實例

<script src="https://cdn.staticfile.net/jquery/1.10.2/jquery.min.js"></script>
<script src="https://cdn.staticfile.net/echarts/4.3.0/echarts.min.js"></script>
</head>
<body><div id="main" style="width: 600px;height:400px;"></div><script type="text/javascript">var myChart = echarts.init(document.getElementById('main'));$.get('https://www.runoob.com/static/js/life-expectancy-table.json', function (data) {var sizeValue = '57%';    // 用于設置網格(grid)的尺寸var symbolSize = 2.5;    // 用于設置散點圖點的大小option = {legend: {},tooltip: {}, toolbox: {left: 'center',feature: {dataZoom: {}}},grid: [{right: sizeValue, bottom: sizeValue},{left: sizeValue, bottom: sizeValue},{right: sizeValue, top: sizeValue},{left: sizeValue, top: sizeValue}],xAxis: [{type: 'value', gridIndex: 0, name: 'Income', axisLabel: {rotate: 50, interval: 0}},{type: 'category', gridIndex: 1, name: 'Country', boundaryGap: false, axisLabel: {rotate: 50, interval: 0}},{type: 'value', gridIndex: 2, name: 'Income', axisLabel: {rotate: 50, interval: 0}},{type: 'value', gridIndex: 3, name: 'Life Expectancy', axisLabel: {rotate: 50, interval: 0}}],yAxis: [{type: 'value', gridIndex: 0, name: 'Life Expectancy'},{type: 'value', gridIndex: 1, name: 'Income'},{type: 'value', gridIndex: 2, name: 'Population'},{type: 'value', gridIndex: 3, name: 'Population'}],dataset: {dimensions: ['Income','Life Expectancy','Population','Country',{name: 'Year', type: 'ordinal'}],source: data},series: [{type: 'scatter',symbolSize: symbolSize,xAxisIndex: 0,yAxisIndex: 0,encode: {x: 'Income',y: 'Life Expectancy',tooltip: [0, 1, 2, 3, 4]}},{type: 'scatter',symbolSize: symbolSize,xAxisIndex: 1,yAxisIndex: 1,encode: {x: 'Country',y: 'Income',tooltip: [0, 1, 2, 3, 4]}},{type: 'scatter',symbolSize: symbolSize,xAxisIndex: 2,yAxisIndex: 2,encode: {x: 'Income',y: 'Population',tooltip: [0, 1, 2, 3, 4]}},{type: 'scatter',symbolSize: symbolSize,xAxisIndex: 3,yAxisIndex: 3,encode: {x: 'Life Expectancy',y: 'Population',tooltip: [0, 1, 2, 3, 4]}}]};myChart.setOption(option);});</script>
</body>

視覺通道(顏色、尺寸等)的映射

視覺元素可以是:

  • symbol: 圖元的圖形類別

  • symbolSize: 圖元的大小

  • color: 圖元的顏色

  • colorAlpha: 圖元的顏色的透明度

  • opacity: 圖元以及其附屬物(如文字標簽)的透明度

  • colorLightness: 顏色的明暗度

  • colorSaturation: 顏色的飽和度

  • colorHue: 顏色的色調

<script src="https://cdn.staticfile.net/echarts/4.3.0/echarts.min.js"></script>
</head>
<body><div id="main" style="width: 600px;height:400px;"></div><script type="text/javascript">var myChart = echarts.init(document.getElementById('main'));var option = {dataset: {source: [['score', 'amount', 'product'],[89.3, 58212, 'Matcha Latte'],[57.1, 78254, 'Milk Tea'],[74.4, 41032, 'Cheese Cocoa'],[50.1, 12755, 'Cheese Brownie'],[89.7, 20145, 'Matcha Cocoa'],[68.1, 79146, 'Tea'],[19.6, 91852, 'Orange Juice'],[10.6, 101852, 'Lemon Juice'],[32.7, 20112, 'Walnut Brownie']]},grid: {containLabel: true},xAxis: {name: 'amount'},yAxis: {type: 'category'},visualMap: {orient: 'horizontal',left: 'center',min: 10,max: 100,text: ['High Score', 'Low Score'],// Map the score column to colordimension: 0,inRange: {color: ['#D7DA8B', '#E15457']}},series: [{type: 'bar',encode: {// Map the "amount" column to X axis.x: 'amount',// Map the "product" column to Y axisy: 'product'}}]};myChart.setOption(option);</script>
</body>

交互聯動

<script src="https://cdn.staticfile.net/echarts/4.3.0/echarts.min.js"></script>
</head>
<body><div id="main" style="width: 600px;height:400px;"></div><script type="text/javascript">var myChart = echarts.init(document.getElementById('main'));setTimeout(function () {option = {legend: {},tooltip: {trigger: 'axis',showContent: false},dataset: {source: [['product', '2012', '2013', '2014', '2015', '2016', '2017'],['Matcha Latte', 41.1, 30.4, 65.1, 53.3, 83.8, 98.7],['Milk Tea', 86.5, 92.1, 85.7, 83.1, 73.4, 55.1],['Cheese Cocoa', 24.1, 67.2, 79.5, 86.4, 65.2, 82.5],['Walnut Brownie', 55.2, 67.1, 69.2, 72.4, 53.9, 39.1]]},xAxis: {type: 'category'},yAxis: {gridIndex: 0},grid: {top: '55%'},series: [{type: 'line', smooth: true, seriesLayoutBy: 'row'},{type: 'line', smooth: true, seriesLayoutBy: 'row'},{type: 'line', smooth: true, seriesLayoutBy: 'row'},{type: 'line', smooth: true, seriesLayoutBy: 'row'},{type: 'pie',id: 'pie',radius: '30%',center: ['50%', '25%'],label: {formatter: '{b}: {@2012} ({d}%)'},encode: {itemName: 'product',value: '2012',tooltip: '2012'}}]};myChart.on('updateAxisPointer', function (event) {var xAxisInfo = event.axesInfo[0];if (xAxisInfo) {var dimension = xAxisInfo.value + 1;myChart.setOption({series: {id: 'pie',label: {formatter: '{b}: {@[' + dimension + ']} ({d}%)'},encode: {value: dimension,tooltip: dimension}}});}});myChart.setOption(option);});</script>
</body>

ECharts 交互組件

dataZoom

dataZoom 組件可以實現通過鼠標滾輪滾動,放大縮小圖表的功能

默認情況下 dataZoom 控制 x 軸,即對 x 軸進行數據窗口縮放數據窗口平移操作

<script src="https://cdn.staticfile.net/echarts/4.3.0/echarts.min.js"></script>
</head>
<body><div id="main" style="width: 600px;height:400px;"></div><script type="text/javascript">var myChart = echarts.init(document.getElementById('main'));var option = {xAxis: {type: 'value'},yAxis: {type: 'value'},dataZoom: [{   // 這個dataZoom組件,默認控制x軸。type: 'slider', // 這個 dataZoom 組件是 slider 型 dataZoom 組件start: 10,      // 左邊在 10% 的位置。end: 60         // 右邊在 60% 的位置。}],series: [{type: 'scatter', // 這是個『散點圖』itemStyle: {opacity: 0.8},symbolSize: function (val) {return val[2] * 40;},data: [["14.616","7.241","0.896"],["3.958","5.701","0.955"],["2.768","8.971","0.669"],["9.051","9.710","0.171"],["14.046","4.182","0.536"],["12.295","1.429","0.962"],["4.417","8.167","0.113"],["0.492","4.771","0.785"],["7.632","2.605","0.645"],["14.242","5.042","0.368"]]}]}// 使用剛指定的配置項和數據顯示圖表。myChart.setOption(option);</script>
</body>

增加 type: 'inside' 的配置信息

<script src="https://cdn.staticfile.net/echarts/4.3.0/echarts.min.js"></script>
</head>
<body><div id="main" style="width: 600px;height:400px;"></div><script type="text/javascript">var myChart = echarts.init(document.getElementById('main'));var option = {xAxis: {type: 'value'},yAxis: {type: 'value'},dataZoom: [{   // 這個dataZoom組件,默認控制x軸。type: 'slider', // 這個 dataZoom 組件是 slider 型 dataZoom 組件start: 10,      // 左邊在 10% 的位置。end: 60         // 右邊在 60% 的位置。},{   // 這個dataZoom組件,也控制x軸。type: 'inside', // 這個 dataZoom 組件是 inside 型 dataZoom 組件start: 10,      // 左邊在 10% 的位置。end: 60         // 右邊在 60% 的位置。}],series: [{type: 'scatter', // 這是個『散點圖』itemStyle: {opacity: 0.8},symbolSize: function (val) {return val[2] * 40;},data: [["14.616","7.241","0.896"],["3.958","5.701","0.955"],["2.768","8.971","0.669"],["9.051","9.710","0.171"],["14.046","4.182","0.536"],["12.295","1.429","0.962"],["4.417","8.167","0.113"],["0.492","4.771","0.785"],["7.632","2.605","0.645"],["14.242","5.042","0.368"]]}]}myChart.setOption(option);</script>
</body>

可以通過 dataZoom.xAxisIndexdataZoom.yAxisIndex 來指定 dataZoom 控制哪個或哪些數軸

<script src="https://cdn.staticfile.net/echarts/4.3.0/echarts.min.js"></script>
</head>
<body><div id="main" style="width: 600px;height:400px;"></div><script type="text/javascript">var myChart = echarts.init(document.getElementById('main'));var data1 = [];var data2 = [];var data3 = [];var random = function (max) {return (Math.random() * max).toFixed(3);};for (var i = 0; i < 500; i++) {data1.push([random(15), random(10), random(1)]);data2.push([random(10), random(10), random(1)]);data3.push([random(15), random(10), random(1)]);}option = {animation: false,legend: {data: ['scatter', 'scatter2', 'scatter3']},tooltip: {},xAxis: {type: 'value',min: 'dataMin',max: 'dataMax',splitLine: {show: true}},yAxis: {type: 'value',min: 'dataMin',max: 'dataMax',splitLine: {show: true}},dataZoom: [{type: 'slider',show: true,xAxisIndex: [0],start: 1,end: 35},{type: 'slider',show: true,yAxisIndex: [0],left: '93%',start: 29,end: 36},{type: 'inside',xAxisIndex: [0],start: 1,end: 35},{type: 'inside',yAxisIndex: [0],start: 29,end: 36}],series: [{name: 'scatter',type: 'scatter',itemStyle: {normal: {opacity: 0.8}},symbolSize: function (val) {return val[2] * 40;},data: data1},{name: 'scatter2',type: 'scatter',itemStyle: {normal: {opacity: 0.8}},symbolSize: function (val) {return val[2] * 40;},data: data2},{name: 'scatter3',type: 'scatter',itemStyle: {normal: {opacity: 0.8,}},symbolSize: function (val) {return val[2] * 40;},data: data3}]}myChart.setOption(option);</script>
</body>

ECharts 響應式

left/right/top/bottom/width/height 定位方式

這六個量中,每個量都可以是『絕對值』或者『百分比』或者『位置描述』

  • 絕對值

    單位是瀏覽器像素(px),用 number 形式書寫(不寫單位)。例如 {left: 23, height: 400}

  • 百分比

    表示占 DOM 容器高寬的百分之多少,用 string 形式書寫。例如 {right: '30%', bottom: '40%'}

  • 位置描述

    • 可以設置 left: 'center',表示水平居中

    • 可以設置 top: 'middle',表示垂直居中

center / radius 定位方式

  • center

    是一個數組,表示 [x, y],其中,xy可以是『絕對值』或者『百分比』,含義和前述相同

  • radius

    是一個數組,表示 [內半徑, 外半徑],其中,內外半徑可以是『絕對值』或者『百分比』,含義和前述相同

    在自適應容器大小時,百分比設置是很有用的

橫向(horizontal)和縱向(vertical)

ECharts的『外觀狹長』型的組件(如 legend、visualMap、dataZoom、timeline等),大多提供了『橫向布局』『縱向布局』的選擇。例如,在細長的移動端屏幕上,可能適合使用『縱向布局』;在PC寬屏上,可能適合使用『橫向布局』

橫縱向布局的設置,一般在『組件』或者『系列』的 orient 或者 layout 配置項上,設置為 'horizontal' 或者 'vertical'

<script src="https://cdn.staticfile.net/jquery/2.2.4/jquery.min.js"></script>
<script src="https://cdn.staticfile.net/echarts/4.3.0/echarts.min.js"></script>
</head>
<body><div id="main" style="width: 600px;height:400px;"></div><script type="text/javascript">var myChart = echarts.init(document.getElementById('main'));$.when($.getScript('https://www.runoob.com/static/js/timelineGDP.js'),$.getScript('https://www.runoob.com/static/js/draggable.js')).done(function () {draggable.init($('div[_echarts_instance_]')[0],myChart,{width: 700,height: 400,throttle: 70});myChart.hideLoading();option = {baseOption: {title : {text: '南丁格爾玫瑰圖',subtext: '純屬虛構',x:'center'},tooltip : {trigger: 'item',formatter: "{a} <br/>{b} : {c} ({d}%)"},legend: {data:['rose1','rose2','rose3','rose4','rose5','rose6','rose7','rose8']},toolbox: {show : true,feature : {mark : {show: true},dataView : {show: true, readOnly: false},magicType : {show: true,type: ['pie', 'funnel']},restore : {show: true},saveAsImage : {show: true}}},calculable : true,series : [{name:'半徑模式',type:'pie',roseType : 'radius',label: {normal: {show: false},emphasis: {show: true}},lableLine: {normal: {show: false},emphasis: {show: true}},data:[{value:10, name:'rose1'},{value:5, name:'rose2'},{value:15, name:'rose3'},{value:25, name:'rose4'},{value:20, name:'rose5'},{value:35, name:'rose6'},{value:30, name:'rose7'},{value:40, name:'rose8'}]},{name:'面積模式',type:'pie',roseType : 'area',data:[{value:10, name:'rose1'},{value:5, name:'rose2'},{value:15, name:'rose3'},{value:25, name:'rose4'},{value:20, name:'rose5'},{value:35, name:'rose6'},{value:30, name:'rose7'},{value:40, name:'rose8'}]}]},media: [{option: {legend: {right: 'center',bottom: 0,orient: 'horizontal'},series: [{radius: [20, '50%'],center: ['25%', '50%']},{radius: [30, '50%'],center: ['75%', '50%']}]}},{query: {minAspectRatio: 1},option: {legend: {right: 'center',bottom: 0,orient: 'horizontal'},series: [{radius: [20, '50%'],center: ['25%', '50%']},{radius: [30, '50%'],center: ['75%', '50%']}]}},{query: {maxAspectRatio: 1},option: {legend: {right: 'center',bottom: 0,orient: 'horizontal'},series: [{radius: [20, '50%'],center: ['50%', '30%']},{radius: [30, '50%'],center: ['50%', '70%']}]}},{query: {maxWidth: 500},option: {legend: {right: 10,top: '15%',orient: 'vertical'},series: [{radius: [20, '50%'],center: ['50%', '30%']},{radius: [30, '50%'],center: ['50%', '75%']}]}}]};myChart.setOption(option);});</script>
</body>

要在 option 中設置 Media Query 須遵循如下格式:

option = {baseOption: { // 這里是基本的『原子option』。title: {...},legend: {...},series: [{...}, {...}, ...],...},media: [ // 這里定義了 media query 的逐條規則。{query: {...},   // 這里寫規則。option: {       // 這里寫此規則滿足下的option。legend: {...},...}},{query: {...},   // 第二個規則。option: {       // 第二個規則對應的option。legend: {...},...}},{                   // 這條里沒有寫規則,表示『默認』,option: {       // 即所有規則都不滿足時,采納這個option。legend: {...},...}}]
};
media: [...,{query: {maxAspectRatio: 1           // 當長寬比小于1時。},option: {legend: {                   // legend 放在底部中間。right: 'center',bottom: 0,orient: 'horizontal'    // legend 橫向布局。},series: [                   // 兩個餅圖左右布局。{radius: [20, '50%'],center: ['50%', '30%']},{radius: [30, '50%'],center: ['50%', '70%']}]}},{query: {maxWidth: 500               // 當容器寬度小于 500 時。},option: {legend: {right: 10,              // legend 放置在右側中間。top: '15%',orient: 'vertical'      // 縱向布局。},series: [                   // 兩個餅圖上下布局。{radius: [20, '50%'],center: ['50%', '30%']},{radius: [30, '50%'],center: ['50%', '75%']}]}},...
]
<script src="https://cdn.staticfile.net/jquery/2.2.4/jquery.min.js"></script>
<script src="https://cdn.staticfile.net/echarts/4.3.0/echarts.min.js"></script>
</head>
<body><div id="main" style="width: 600px;height:400px;"></div><script type="text/javascript">var myChart = echarts.init(document.getElementById('main'));$.when($.getScript('https://www.runoob.com/static/js/timelineGDP.js'),$.getScript('https://www.runoob.com/static/js/draggable.js')).done(function () {draggable.init($('div[_echarts_instance_]')[0],myChart,{width: 700,height: 630,lockY: true,throttle: 70});myChart.hideLoading();var categoryData = ['北京','天津','河北','山西','內蒙古','遼寧','吉林','黑龍江','上海','江蘇','浙江','安徽','福建','江西','山東','河南','湖北','湖南','廣東','廣西','海南','重慶','四川','貴州','云南','西藏','陜西','甘肅','青海','寧夏','新疆'];option = {baseOption: {timeline: {axisType: 'category',autoPlay: true,playInterval: 1000,data: ['2002-01-01', '2003-01-01', '2004-01-01','2005-01-01', '2006-01-01', '2007-01-01','2008-01-01', '2009-01-01', '2010-01-01','2011-01-01'],label: {formatter : function(s) {return (new Date(s)).getFullYear();}}},title: {subtext: 'Media Query 示例'},tooltip: {trigger:'axis',axisPointer: {type: 'shadow'}},xAxis: {type: 'value',name: 'GDP(億元)',max: 30000,data: null},yAxis: {type: 'category',data: categoryData,axisLabel: {interval: 0},splitLine: {show: false}},legend: {data: ['第一產業', '第二產業', '第三產業', 'GDP', '金融', '房地產'],selected: {'GDP': false, '金融': false, '房地產': false}},calculable : true,series: [{name: 'GDP', type: 'bar'},{name: '金融', type: 'bar'},{name: '房地產', type: 'bar'},{name: '第一產業', type: 'bar'},{name: '第二產業', type: 'bar'},{name: '第三產業', type: 'bar'},{name: 'GDP占比', type: 'pie'}]},media: [{option: {legend: {orient: 'horizontal',left: 'right',itemGap: 10},grid: {left: '10%',top: 80,right: 90,bottom: 100},xAxis: {nameLocation: 'end',nameGap: 10,splitNumber: 5,splitLine: {show: true}},timeline: {orient: 'horizontal',inverse: false,left: '20%',right: '20%',bottom: 10,height: 40},series: [{name: 'GDP占比', center: ['75%', '30%'], radius: '28%'}]}},{query: {maxWidth: 670, minWidth: 550},option: {legend: {orient: 'horizontal',left: 200,itemGap: 5},grid: {left: '10%',top: 80,right: 90,bottom: 100},xAxis: {nameLocation: 'end',nameGap: 10,splitNumber: 5,splitLine: {show: true}},timeline: {orient: 'horizontal',inverse: false,left: '20%',right: '20%',bottom: 10,height: 40},series: [{name: 'GDP占比', center: ['75%', '30%'], radius: '28%'}]}},{query: {maxWidth: 550},option: {legend: {orient: 'vertical',left: 'right',itemGap: 5},grid: {left: 55,top: '32%',right: 100,bottom: 50},xAxis: {nameLocation: 'middle',nameGap: 25,splitNumber: 3},timeline: {orient: 'vertical',inverse: true,right: 10,top: 150,bottom: 10,width: 55},series: [{name: 'GDP占比', center: ['45%', '20%'], radius: '28%'}]}}],options: [{title: {text: '2002全國宏觀經濟指標'},series: [{data: dataMap.dataGDP['2002']},{data: dataMap.dataFinancial['2002']},{data: dataMap.dataEstate['2002']},{data: dataMap.dataPI['2002']},{data: dataMap.dataSI['2002']},{data: dataMap.dataTI['2002']},{data: [{name: '第一產業', value: dataMap.dataPI['2002sum']},{name: '第二產業', value: dataMap.dataSI['2002sum']},{name: '第三產業', value: dataMap.dataTI['2002sum']}]}]},{title : {text: '2003全國宏觀經濟指標'},series : [{data: dataMap.dataGDP['2003']},{data: dataMap.dataFinancial['2003']},{data: dataMap.dataEstate['2003']},{data: dataMap.dataPI['2003']},{data: dataMap.dataSI['2003']},{data: dataMap.dataTI['2003']},{data: [{name: '第一產業', value: dataMap.dataPI['2003sum']},{name: '第二產業', value: dataMap.dataSI['2003sum']},{name: '第三產業', value: dataMap.dataTI['2003sum']}]}]},{title : {text: '2004全國宏觀經濟指標'},series : [{data: dataMap.dataGDP['2004']},{data: dataMap.dataFinancial['2004']},{data: dataMap.dataEstate['2004']},{data: dataMap.dataPI['2004']},{data: dataMap.dataSI['2004']},{data: dataMap.dataTI['2004']},{data: [{name: '第一產業', value: dataMap.dataPI['2004sum']},{name: '第二產業', value: dataMap.dataSI['2004sum']},{name: '第三產業', value: dataMap.dataTI['2004sum']}]}]},{title : {text: '2005全國宏觀經濟指標'},series : [{data: dataMap.dataGDP['2005']},{data: dataMap.dataFinancial['2005']},{data: dataMap.dataEstate['2005']},{data: dataMap.dataPI['2005']},{data: dataMap.dataSI['2005']},{data: dataMap.dataTI['2005']},{data: [{name: '第一產業', value: dataMap.dataPI['2005sum']},{name: '第二產業', value: dataMap.dataSI['2005sum']},{name: '第三產業', value: dataMap.dataTI['2005sum']}]}]},{title : {text: '2006全國宏觀經濟指標'},series : [{data: dataMap.dataGDP['2006']},{data: dataMap.dataFinancial['2006']},{data: dataMap.dataEstate['2006']},{data: dataMap.dataPI['2006']},{data: dataMap.dataSI['2006']},{data: dataMap.dataTI['2006']},{data: [{name: '第一產業', value: dataMap.dataPI['2006sum']},{name: '第二產業', value: dataMap.dataSI['2006sum']},{name: '第三產業', value: dataMap.dataTI['2006sum']}]}]},{title : {text: '2007全國宏觀經濟指標'},series : [{data: dataMap.dataGDP['2007']},{data: dataMap.dataFinancial['2007']},{data: dataMap.dataEstate['2007']},{data: dataMap.dataPI['2007']},{data: dataMap.dataSI['2007']},{data: dataMap.dataTI['2007']},{data: [{name: '第一產業', value: dataMap.dataPI['2007sum']},{name: '第二產業', value: dataMap.dataSI['2007sum']},{name: '第三產業', value: dataMap.dataTI['2007sum']}]}]},{title : {text: '2008全國宏觀經濟指標'},series : [{data: dataMap.dataGDP['2008']},{data: dataMap.dataFinancial['2008']},{data: dataMap.dataEstate['2008']},{data: dataMap.dataPI['2008']},{data: dataMap.dataSI['2008']},{data: dataMap.dataTI['2008']},{data: [{name: '第一產業', value: dataMap.dataPI['2008sum']},{name: '第二產業', value: dataMap.dataSI['2008sum']},{name: '第三產業', value: dataMap.dataTI['2008sum']}]}]},{title : {text: '2009全國宏觀經濟指標'},series : [{data: dataMap.dataGDP['2009']},{data: dataMap.dataFinancial['2009']},{data: dataMap.dataEstate['2009']},{data: dataMap.dataPI['2009']},{data: dataMap.dataSI['2009']},{data: dataMap.dataTI['2009']},{data: [{name: '第一產業', value: dataMap.dataPI['2009sum']},{name: '第二產業', value: dataMap.dataSI['2009sum']},{name: '第三產業', value: dataMap.dataTI['2009sum']}]}]},{title : {text: '2010全國宏觀經濟指標'},series : [{data: dataMap.dataGDP['2010']},{data: dataMap.dataFinancial['2010']},{data: dataMap.dataEstate['2010']},{data: dataMap.dataPI['2010']},{data: dataMap.dataSI['2010']},{data: dataMap.dataTI['2010']},{data: [{name: '第一產業', value: dataMap.dataPI['2010sum']},{name: '第二產業', value: dataMap.dataSI['2010sum']},{name: '第三產業', value: dataMap.dataTI['2010sum']}]}]},{title : {text: '2011全國宏觀經濟指標'},series : [{data: dataMap.dataGDP['2011']},{data: dataMap.dataFinancial['2011']},{data: dataMap.dataEstate['2011']},{data: dataMap.dataPI['2011']},{data: dataMap.dataSI['2011']},{data: dataMap.dataTI['2011']},{data: [{name: '第一產業', value: dataMap.dataPI['2011sum']},{name: '第二產業', value: dataMap.dataSI['2011sum']},{name: '第三產業', value: dataMap.dataTI['2011sum']}]}]}]};myChart.setOption(option);});</script>
</body>

ECharts 數據的視覺映射

  • 圖形類別(symbol

  • 圖形大小(symbolSize

  • 顏色(color

  • 透明度(opacity

  • 顏色透明度(colorAlpha

  • 顏色明暗度(colorLightness

  • 顏色飽和度(colorSaturation

  • 色調(colorHue

數據和維度

series.data最常見的形式 是線性表,即一個普通數組:

series: {data: [{       // 這里每一個項就是數據項(dataItem)value: 2323, // 這是數據項的數據值(value)itemStyle: {...}},1212,   // 也可以直接是 dataItem 的 value,這更常見。2323,   // 每個 value 都是『一維』的。4343,3434]
}
series: {data: [{                        // 這里每一個項就是數據項(dataItem)value: [3434, 129,  '圣馬力諾'], // 這是數據項的數據值(value)itemStyle: {...}},[1212, 5454, '梵蒂岡'],   // 也可以直接是 dataItem 的 value,這更常見。[2323, 3223, '瑙魯'],     // 每個 value 都是『三維』的,每列是一個維度。[4343, 23,   '圖瓦盧']    // 假如是『氣泡圖』,常見第一維度映射到x軸,// 第二維度映射到y軸,// 第三維度映射到氣泡半徑(symbolSize)]
}

visualMap 組件

visualMap 組件定義了把數據的指定維度映射到對應的視覺元素上

option = {visualMap: [{ // 第一個 visualMap 組件type: 'continuous', // 定義為連續型 visualMap...},{ // 第二個 visualMap 組件type: 'piecewise', // 定義為分段型 visualMap...}],...
};
<html style="height: 100%"><head><meta charset="utf-8"></head><body style="height: 100%; margin: 0"><div id="container" style="height: 100%"></div><script type="text/javascript" src="https://cdn.jsdelivr.net/npm/echarts/dist/echarts.min.js"></script><script type="text/javascript" src="https://cdn.jsdelivr.net/npm/echarts-gl/dist/echarts-gl.min.js"></script><script type="text/javascript" src="https://cdn.jsdelivr.net/npm/echarts-stat/dist/ecStat.min.js"></script><script type="text/javascript" src="https://cdn.jsdelivr.net/npm/echarts/dist/extension/dataTool.min.js"></script><script type="text/javascript" src="https://cdn.jsdelivr.net/npm/echarts/map/js/china.js"></script><script type="text/javascript" src="https://cdn.jsdelivr.net/npm/echarts/map/js/world.js"></script><script type="text/javascript" src="https://cdn.jsdelivr.net/npm/echarts/dist/extension/bmap.min.js"></script><script type="text/javascript">var dom = document.getElementById("container");var myChart = echarts.init(dom);var app = {};option = null;var geoCoordMap = {"海門":[121.15,31.89],"鄂爾多斯":[109.781327,39.608266],"招遠":[120.38,37.35],"舟山":[122.207216,29.985295],"齊齊哈爾":[123.97,47.33],"鹽城":[120.13,33.38],"赤峰":[118.87,42.28],"青島":[120.33,36.07],"乳山":[121.52,36.89],"金昌":[102.188043,38.520089],"泉州":[118.58,24.93],"萊西":[120.53,36.86],"日照":[119.46,35.42],"膠南":[119.97,35.88],"南通":[121.05,32.08],"拉薩":[91.11,29.97],"云浮":[112.02,22.93],"梅州":[116.1,24.55],"文登":[122.05,37.2],"上海":[121.48,31.22],"攀枝花":[101.718637,26.582347],"威海":[122.1,37.5],"承德":[117.93,40.97],"廈門":[118.1,24.46],"汕尾":[115.375279,22.786211],"潮州":[116.63,23.68],"丹東":[124.37,40.13],"太倉":[121.1,31.45],"曲靖":[103.79,25.51],"煙臺":[121.39,37.52],"福州":[119.3,26.08],"瓦房店":[121.979603,39.627114],"即墨":[120.45,36.38],"撫順":[123.97,41.97],"玉溪":[102.52,24.35],"張家口":[114.87,40.82],"陽泉":[113.57,37.85],"萊州":[119.942327,37.177017],"湖州":[120.1,30.86],"汕頭":[116.69,23.39],"昆山":[120.95,31.39],"寧波":[121.56,29.86],"湛江":[110.359377,21.270708],"揭陽":[116.35,23.55],"榮成":[122.41,37.16],"連云港":[119.16,34.59],"葫蘆島":[120.836932,40.711052],"常熟":[120.74,31.64],"東莞":[113.75,23.04],"河源":[114.68,23.73],"淮安":[119.15,33.5],"泰州":[119.9,32.49],"南寧":[108.33,22.84],"營口":[122.18,40.65],"惠州":[114.4,23.09],"江陰":[120.26,31.91],"蓬萊":[120.75,37.8],"韶關":[113.62,24.84],"嘉峪關":[98.289152,39.77313],"廣州":[113.23,23.16],"延安":[109.47,36.6],"太原":[112.53,37.87],"清遠":[113.01,23.7],"中山":[113.38,22.52],"昆明":[102.73,25.04],"壽光":[118.73,36.86],"盤錦":[122.070714,41.119997],"長治":[113.08,36.18],"深圳":[114.07,22.62],"珠海":[113.52,22.3],"宿遷":[118.3,33.96],"咸陽":[108.72,34.36],"銅川":[109.11,35.09],"平度":[119.97,36.77],"佛山":[113.11,23.05],"海口":[110.35,20.02],"江門":[113.06,22.61],"章丘":[117.53,36.72],"肇慶":[112.44,23.05],"大連":[121.62,38.92],"臨汾":[111.5,36.08],"吳江":[120.63,31.16],"石嘴山":[106.39,39.04],"沈陽":[123.38,41.8],"蘇州":[120.62,31.32],"茂名":[110.88,21.68],"嘉興":[120.76,30.77],"長春":[125.35,43.88],"膠州":[120.03336,36.264622],"銀川":[106.27,38.47],"張家港":[120.555821,31.875428],"三門峽":[111.19,34.76],"錦州":[121.15,41.13],"南昌":[115.89,28.68],"柳州":[109.4,24.33],"三亞":[109.511909,18.252847],"自貢":[104.778442,29.33903],"吉林":[126.57,43.87],"陽江":[111.95,21.85],"瀘州":[105.39,28.91],"西寧":[101.74,36.56],"宜賓":[104.56,29.77],"呼和浩特":[111.65,40.82],"成都":[104.06,30.67],"大同":[113.3,40.12],"鎮江":[119.44,32.2],"桂林":[110.28,25.29],"張家界":[110.479191,29.117096],"宜興":[119.82,31.36],"北海":[109.12,21.49],"西安":[108.95,34.27],"金壇":[119.56,31.74],"東營":[118.49,37.46],"牡丹江":[129.58,44.6],"遵義":[106.9,27.7],"紹興":[120.58,30.01],"揚州":[119.42,32.39],"常州":[119.95,31.79],"濰坊":[119.1,36.62],"重慶":[106.54,29.59],"臺州":[121.420757,28.656386],"南京":[118.78,32.04],"濱州":[118.03,37.36],"貴陽":[106.71,26.57],"無錫":[120.29,31.59],"本溪":[123.73,41.3],"克拉瑪依":[84.77,45.59],"渭南":[109.5,34.52],"馬鞍山":[118.48,31.56],"寶雞":[107.15,34.38],"焦作":[113.21,35.24],"句容":[119.16,31.95],"北京":[116.46,39.92],"徐州":[117.2,34.26],"衡水":[115.72,37.72],"包頭":[110,40.58],"綿陽":[104.73,31.48],"烏魯木齊":[87.68,43.77],"棗莊":[117.57,34.86],"杭州":[120.19,30.26],"淄博":[118.05,36.78],"鞍山":[122.85,41.12],"溧陽":[119.48,31.43],"庫爾勒":[86.06,41.68],"安陽":[114.35,36.1],"開封":[114.35,34.79],"濟南":[117,36.65],"德陽":[104.37,31.13],"溫州":[120.65,28.01],"九江":[115.97,29.71],"邯鄲":[114.47,36.6],"臨安":[119.72,30.23],"蘭州":[103.73,36.03],"滄州":[116.83,38.33],"臨沂":[118.35,35.05],"南充":[106.110698,30.837793],"天津":[117.2,39.13],"富陽":[119.95,30.07],"泰安":[117.13,36.18],"諸暨":[120.23,29.71],"鄭州":[113.65,34.76],"哈爾濱":[126.63,45.75],"聊城":[115.97,36.45],"蕪湖":[118.38,31.33],"唐山":[118.02,39.63],"平頂山":[113.29,33.75],"邢臺":[114.48,37.05],"德州":[116.29,37.45],"濟寧":[116.59,35.38],"荊州":[112.239741,30.335165],"宜昌":[111.3,30.7],"義烏":[120.06,29.32],"麗水":[119.92,28.45],"洛陽":[112.44,34.7],"秦皇島":[119.57,39.95],"株洲":[113.16,27.83],"石家莊":[114.48,38.03],"萊蕪":[117.67,36.19],"常德":[111.69,29.05],"保定":[115.48,38.85],"湘潭":[112.91,27.87],"金華":[119.64,29.12],"岳陽":[113.09,29.37],"長沙":[113,28.21],"衢州":[118.88,28.97],"廊坊":[116.7,39.53],"菏澤":[115.480656,35.23375],"合肥":[117.27,31.86],"武漢":[114.31,30.52],"大慶":[125.03,46.58]};var convertData = function (data) {var res = [];for (var i = 0; i < data.length; i++) {var geoCoord = geoCoordMap[data[i].name];if (geoCoord) {res.push(geoCoord.concat(data[i].value));}}return res;};option = {backgroundColor: '#404a59',title: {text: '全國主要城市空氣質量',subtext: 'data from PM25.in',sublink: 'http://www.pm25.in',left: 'center',textStyle: {color: '#fff'}},tooltip: {trigger: 'item'},legend: {orient: 'vertical',top: 'bottom',left: 'right',data:['pm2.5'],textStyle: {color: '#fff'}},visualMap: {min: 0,max: 300,splitNumber: 5,color: ['#d94e5d','#eac736','#50a3ba'],textStyle: {color: '#fff'}},geo: {map: 'china',label: {emphasis: {show: false}},itemStyle: {normal: {areaColor: '#323c48',borderColor: '#111'},emphasis: {areaColor: '#2a333d'}}},series: [{name: 'pm2.5',type: 'scatter',coordinateSystem: 'geo',data: convertData([{name: "海門", value: 9},{name: "鄂爾多斯", value: 12},{name: "招遠", value: 12},{name: "舟山", value: 12},{name: "齊齊哈爾", value: 14},{name: "鹽城", value: 15},{name: "赤峰", value: 16},{name: "青島", value: 18},{name: "乳山", value: 18},{name: "金昌", value: 19},{name: "泉州", value: 21},{name: "萊西", value: 21},{name: "日照", value: 21},{name: "膠南", value: 22},{name: "南通", value: 23},{name: "拉薩", value: 24},{name: "云浮", value: 24},{name: "梅州", value: 25},{name: "文登", value: 25},{name: "上海", value: 25},{name: "攀枝花", value: 25},{name: "威海", value: 25},{name: "承德", value: 25},{name: "廈門", value: 26},{name: "汕尾", value: 26},{name: "潮州", value: 26},{name: "丹東", value: 27},{name: "太倉", value: 27},{name: "曲靖", value: 27},{name: "煙臺", value: 28},{name: "福州", value: 29},{name: "瓦房店", value: 30},{name: "即墨", value: 30},{name: "撫順", value: 31},{name: "玉溪", value: 31},{name: "張家口", value: 31},{name: "陽泉", value: 31},{name: "萊州", value: 32},{name: "湖州", value: 32},{name: "汕頭", value: 32},{name: "昆山", value: 33},{name: "寧波", value: 33},{name: "湛江", value: 33},{name: "揭陽", value: 34},{name: "榮成", value: 34},{name: "連云港", value: 35},{name: "葫蘆島", value: 35},{name: "常熟", value: 36},{name: "東莞", value: 36},{name: "河源", value: 36},{name: "淮安", value: 36},{name: "泰州", value: 36},{name: "南寧", value: 37},{name: "營口", value: 37},{name: "惠州", value: 37},{name: "江陰", value: 37},{name: "蓬萊", value: 37},{name: "韶關", value: 38},{name: "嘉峪關", value: 38},{name: "廣州", value: 38},{name: "延安", value: 38},{name: "太原", value: 39},{name: "清遠", value: 39},{name: "中山", value: 39},{name: "昆明", value: 39},{name: "壽光", value: 40},{name: "盤錦", value: 40},{name: "長治", value: 41},{name: "深圳", value: 41},{name: "珠海", value: 42},{name: "宿遷", value: 43},{name: "咸陽", value: 43},{name: "銅川", value: 44},{name: "平度", value: 44},{name: "佛山", value: 44},{name: "海口", value: 44},{name: "江門", value: 45},{name: "章丘", value: 45},{name: "肇慶", value: 46},{name: "大連", value: 47},{name: "臨汾", value: 47},{name: "吳江", value: 47},{name: "石嘴山", value: 49},{name: "沈陽", value: 50},{name: "蘇州", value: 50},{name: "茂名", value: 50},{name: "嘉興", value: 51},{name: "長春", value: 51},{name: "膠州", value: 52},{name: "銀川", value: 52},{name: "張家港", value: 52},{name: "三門峽", value: 53},{name: "錦州", value: 54},{name: "南昌", value: 54},{name: "柳州", value: 54},{name: "三亞", value: 54},{name: "自貢", value: 56},{name: "吉林", value: 56},{name: "陽江", value: 57},{name: "瀘州", value: 57},{name: "西寧", value: 57},{name: "宜賓", value: 58},{name: "呼和浩特", value: 58},{name: "成都", value: 58},{name: "大同", value: 58},{name: "鎮江", value: 59},{name: "桂林", value: 59},{name: "張家界", value: 59},{name: "宜興", value: 59},{name: "北海", value: 60},{name: "西安", value: 61},{name: "金壇", value: 62},{name: "東營", value: 62},{name: "牡丹江", value: 63},{name: "遵義", value: 63},{name: "紹興", value: 63},{name: "揚州", value: 64},{name: "常州", value: 64},{name: "濰坊", value: 65},{name: "重慶", value: 66},{name: "臺州", value: 67},{name: "南京", value: 67},{name: "濱州", value: 70},{name: "貴陽", value: 71},{name: "無錫", value: 71},{name: "本溪", value: 71},{name: "克拉瑪依", value: 72},{name: "渭南", value: 72},{name: "馬鞍山", value: 72},{name: "寶雞", value: 72},{name: "焦作", value: 75},{name: "句容", value: 75},{name: "北京", value: 79},{name: "徐州", value: 79},{name: "衡水", value: 80},{name: "包頭", value: 80},{name: "綿陽", value: 80},{name: "烏魯木齊", value: 84},{name: "棗莊", value: 84},{name: "杭州", value: 84},{name: "淄博", value: 85},{name: "鞍山", value: 86},{name: "溧陽", value: 86},{name: "庫爾勒", value: 86},{name: "安陽", value: 90},{name: "開封", value: 90},{name: "濟南", value: 92},{name: "德陽", value: 93},{name: "溫州", value: 95},{name: "九江", value: 96},{name: "邯鄲", value: 98},{name: "臨安", value: 99},{name: "蘭州", value: 99},{name: "滄州", value: 100},{name: "臨沂", value: 103},{name: "南充", value: 104},{name: "天津", value: 105},{name: "富陽", value: 106},{name: "泰安", value: 112},{name: "諸暨", value: 112},{name: "鄭州", value: 113},{name: "哈爾濱", value: 114},{name: "聊城", value: 116},{name: "蕪湖", value: 117},{name: "唐山", value: 119},{name: "平頂山", value: 119},{name: "邢臺", value: 119},{name: "德州", value: 120},{name: "濟寧", value: 120},{name: "荊州", value: 127},{name: "宜昌", value: 130},{name: "義烏", value: 132},{name: "麗水", value: 133},{name: "洛陽", value: 134},{name: "秦皇島", value: 136},{name: "株洲", value: 143},{name: "石家莊", value: 147},{name: "萊蕪", value: 148},{name: "常德", value: 152},{name: "保定", value: 153},{name: "湘潭", value: 154},{name: "金華", value: 157},{name: "岳陽", value: 169},{name: "長沙", value: 175},{name: "衢州", value: 177},{name: "廊坊", value: 193},{name: "菏澤", value: 194},{name: "合肥", value: 229},{name: "武漢", value: 273},{name: "大慶", value: 279}]),symbolSize: 12,label: {normal: {show: false},emphasis: {show: false}},itemStyle: {emphasis: {borderColor: '#fff',borderWidth: 1}}}]};if (option && typeof option === "object") {myChart.setOption(option, true);}</script></body>

視覺映射方式的配置

visualMap 中可以指定數據的指定維度映射到對應的視覺元素上

option = {visualMap: [{type: 'piecewise'min: 0,max: 5000,dimension: 3,       // series.data 的第四個維度(即 value[3])被映射seriesIndex: 4,     // 對第四個系列進行映射。inRange: {          // 選中范圍中的視覺配置color: ['blue', '#121122', 'red'], // 定義了圖形顏色映射的顏色列表,// 數據最小值映射到'blue'上,// 最大值映射到'red'上,// 其余自動線性計算。symbolSize: [30, 100]               // 定義了圖形尺寸的映射范圍,// 數據最小值映射到30上,// 最大值映射到100上,// 其余自動線性計算。},outOfRange: {       // 選中范圍外的視覺配置symbolSize: [30, 100]}},...]
};
option = {visualMap: [{...,inRange: {          // 選中范圍中的視覺配置colorLightness: [0.2, 1], // 映射到明暗度上。也就是對本來的顏色進行明暗度處理。// 本來的顏色可能是從全局色板中選取的顏色,visualMap組件并不關心。symbolSize: [30, 100]},...},...]
};

ECharts 事件處理

ECharts 中我們可以通過監聽用戶的操作行為來回調對應的函數

ECharts 通過 on 方法來監聽用戶的行為,例如監控用戶的點擊行為

ECharts 中事件分為兩種類型:

用戶鼠標操作點擊,如 'click'、'dblclick'、'mousedown'、'mousemove'、'mouseup'、'mouseover'、'mouseout'、'globalout'、'contextmenu' 事件

還有一種是用戶在使用可以交互的組件后觸發的行為事件,例如在切換圖例開關時觸發的 'legendselectchanged'事件),數據區域縮放時觸發的'datazoom'事件等等

myChart.on('click', function (params) {// 在用戶點擊后控制臺打印數據的名稱console.log(params);
});
myChart.on('legendselectchanged', function (params) {console.log(params);
});
chart.on('click', 'series.line', function (params) {console.log(params);
});
chart.on('mouseover', {seriesIndex: 1, name: 'xx'}, function (params) {console.log(params);
});

鼠標事件

ECharts 支持的鼠標事件類型,包括 'click'、'dblclick'、'mousedown'、'mousemove'、'mouseup'、'mouseover'、'mouseout'、'globalout'、'contextmenu' 事件

<script src="https://cdn.staticfile.net/echarts/4.3.0/echarts.min.js"></script>
</head>
<body><div id="main" style="width: 600px;height:400px;"></div><script type="text/javascript">var myChart = echarts.init(document.getElementById('main'));var option = {xAxis: {data: ["襯衫","羊毛衫","雪紡衫","褲子","高跟鞋","襪子"]},yAxis: {},series: [{name: '銷量',type: 'bar',data: [5, 20, 36, 10, 10, 20]}]};// 使用剛指定的配置項和數據顯示圖表。myChart.setOption(option);// 處理點擊事件并且彈出數據名稱myChart.on('click', function (params) {alert(params.name);});</script>
</body>

組件交互的行為事件

ECharts 中基本上所有的組件交互行為都會觸發相應的事件,常用的事件和事件對應參數在 events 文檔中有列出

下面是監聽一個圖例開關的示例:

<script src="https://cdn.staticfile.net/echarts/4.3.0/echarts.min.js"></script>
</head>
<body><div id="main" style="width: 600px;height:400px;"></div><script type="text/javascript">var myChart = echarts.init(document.getElementById('main'));var option = {xAxis: {data: ["襯衫","羊毛衫","雪紡衫","褲子","高跟鞋","襪子"]},yAxis: {},series: [{name: '銷量',type: 'bar',data: [5, 20, 36, 10, 10, 20]}]};myChart.setOption(option);myChart.on('click', function (params) {alert(params.name);});</script>
</body>

代碼觸發 ECharts 中組件的行為

上面我們只說明了用戶的交互操作,但有時候我們也會需要在程序里調用方法并觸發圖表的行為,比如顯示 tooltip

ECharts通過 dispatchAction({ type: '' }) 來觸發圖表行為,統一管理了所有動作,也可以根據需要去記錄用戶的行為路徑

以上實例用于輪播餅圖中的tooltip

<script src="https://cdn.staticfile.net/echarts/4.3.0/echarts.min.js"></script>
</head>
<body><div id="main"  style="height: 100%;min-height:400px;"></div><script type="text/javascript">var myChart = echarts.init(document.getElementById('main'));var app = {};option = null;var option = {title : {text: '餅圖程序調用高亮示例',x: 'center'},tooltip: {trigger: 'item',formatter: "{a} <br/>{b} : {c} ({d}%)"},legend: {orient: 'vertical',left: 'left',data: ['直接訪問','郵件營銷','聯盟廣告','視頻廣告','搜索引擎']},series : [{name: '訪問來源',type: 'pie',radius : '55%',center: ['50%', '60%'],data:[{value:335, name:'直接訪問'},{value:310, name:'郵件營銷'},{value:234, name:'聯盟廣告'},{value:135, name:'視頻廣告'},{value:1548, name:'搜索引擎'}],itemStyle: {emphasis: {shadowBlur: 10,shadowOffsetX: 0,shadowColor: 'rgba(0, 0, 0, 0.5)'}}}]};app.currentIndex = -1;setInterval(function () {var dataLen = option.series[0].data.length;// 取消之前高亮的圖形myChart.dispatchAction({type: 'downplay',seriesIndex: 0,dataIndex: app.currentIndex});app.currentIndex = (app.currentIndex + 1) % dataLen;// 高亮當前圖形myChart.dispatchAction({type: 'highlight',seriesIndex: 0,dataIndex: app.currentIndex});// 顯示 tooltipmyChart.dispatchAction({type: 'showTip',seriesIndex: 0,dataIndex: app.currentIndex});}, 1000);if (option && typeof option === "object") {myChart.setOption(option, true);}</script>
</body>

ECharts 旭日圖

旭日圖(Sunburst)由多層的環形圖組成,在數據結構上,內圈是外圈的父節點。因此,它既能像餅圖一樣表現局部和整體的占比,又能像矩形樹圖一樣表現層級關系。

ECharts 創建旭日圖很簡單,只需要在 series 配置項中聲明類型為 sunburst 即可,data 數據結構以樹形結構聲明,看下一個簡單的實例:

<script src="https://cdn.staticfile.net/echarts/4.3.0/echarts.min.js"></script>
</head>
<body><div id="main" style="width: 600px;height:400px;"></div><script type="text/javascript">var myChart = echarts.init(document.getElementById('main'));var option = {series: {type: 'sunburst',data: [{name: 'A',value: 10,children: [{value: 3,name: 'Aa'}, {value: 5,name: 'Ab'}]}, {name: 'B',children: [{name: 'Ba',value: 4}, {name: 'Bb',value: 2}]}, {name: 'C',value: 3}]}};myChart.setOption(option);</script>
</body>

顏色等樣式調整

默認情況下會使用全局調色盤 color 分配最內層的顏色,其余層則與其父元素同色

在旭日圖中,扇形塊的顏色有以下三種設置方式:

  • series.data.itemStyle 中設置每個扇形塊的樣式

  • series.levels.itemStyle 中設置每一層的樣式

  • series.itemStyle 中設置整個旭日圖的樣式

上述三者的優先級是從高到低的,也就是說,配置了 series.data.itemStyle 的扇形塊將會覆蓋 series.levels.itemStyleseries.itemStyle 的設置

下面,我們將整體的顏色設為灰色 #aaa,將最內層的顏色設為藍色 blue,將 Aa、B 這兩塊設為紅色 red

<script src="https://cdn.staticfile.net/echarts/4.3.0/echarts.min.js"></script>
</head>
<body><div id="main" style="width: 600px;height:400px;"></div><script type="text/javascript">var myChart = echarts.init(document.getElementById('main'));var option = {series: {type: 'sunburst',data: [{name: 'A',value: 10,children: [{value: 3,name: 'Aa',itemStyle: {color: 'red'}}, {value: 5,name: 'Ab'}]}, {name: 'B',children: [{name: 'Ba',value: 4}, {name: 'Bb',value: 2}],itemStyle: {color: 'red'}}, {name: 'C',value: 3}],itemStyle: {color: '#aaa'},levels: [{// 留給數據下鉆的節點屬性}, {itemStyle: {color: 'blue'}}]}};myChart.setOption(option);</script>
</body>

數據下鉆

旭日圖默認支持數據下鉆,也就是說,當點擊了扇形塊之后,將以該扇形塊的數據作為根節點,進一步顯示該數據的細節

在數據下鉆后,圖形的中間會出現一個用于返回上一層的圖形,該圖形的樣式可以通過 levels[0] 配置

<script src="https://cdn.staticfile.net/echarts/4.3.0/echarts.min.js"></script>
</head>
<body><div id="main" style="width: 600px;height:400px;"></div><script type="text/javascript">var myChart = echarts.init(document.getElementById('main'));var data = [{name: 'Grandpa',children: [{name: 'Uncle Leo',value: 15,children: [{name: 'Cousin Jack',value: 2}, {name: 'Cousin Mary',value: 5,children: [{name: 'Jackson',value: 2}]}, {name: 'Cousin Ben',value: 4}]}, {name: 'Father',value: 10,children: [{name: 'Me',value: 5}, {name: 'Brother Peter',value: 1}]}]}, {name: 'Nancy',children: [{name: 'Uncle Nike',children: [{name: 'Cousin Betty',value: 1}, {name: 'Cousin Jenny',value: 2}]}]}];option = {series: {type: 'sunburst',// highlightPolicy: 'ancestor',data: data,radius: [0, '90%'],label: {rotate: 'radial'}}};myChart.setOption(option);</script>
</body>

高亮相關扇形塊

旭日圖支持鼠標移動到某扇形塊時,高亮相關數據塊的操作,可以通過設置 highlightPolicy,包括以下幾種高亮方式:

  • 'descendant'(默認值):高亮鼠標移動所在扇形塊與其后代元素;

  • 'ancestor':高亮鼠標所在扇形塊與其祖先元素;

  • 'self':僅高亮鼠標所在扇形塊;

  • 'none':不會淡化(downplay)其他元素

https://www.runoob.com/echarts/echarts-sunburst.html

Ajax

簡介

  • AJAX = Asynchronous JavaScript and XML(異步的 JavaScript 和 XML)

  • AJAX 是一種在無需重新加載整個網頁的情況下,能夠更新部分網頁的技術

  • Ajax的核心是XMLHttpRequest對象(XHR)。XHR為向服務器發送請求和解析服務器響應提供了接口。能夠以異步方式從服務器獲取新數據

偽造Ajax - iframe標簽

<!DOCTYPE html>
<html><head lang="en"><meta charset="UTF-8"><title>kuangshen</title></head><body><script type="text/javascript">window.onload = function(){var myDate = new Date();document.getElementById('currentTime').innerText = myDate.getTime();};function LoadPage(){var targetUrl = ?document.getElementById('url').value;console.log(targetUrl);document.getElementById("iframePosition").src = targetUrl;}</script><div><p>請輸入要加載的地址:<span id="currentTime"></span></p><p><input id="url" type="text" value="https://www.baidu.com/"/><input type="button" value="提交" οnclick="LoadPage()"></p></div><div><h3>加載頁面位置:</h3><iframe id="iframePosition" style="width: 100%;height: 500px;"></iframe></div></body>
</html>

利用AJAX可以做:

  • 注冊時,輸入用戶名自動檢測用戶是否已經存在

  • 登陸時,提示用戶名密碼錯誤

  • 刪除數據行時,將行ID發送到后臺,后臺在數據庫中刪除,數據庫刪除成功后,在頁面DOM中將數據行也刪除

jQuery.ajax

code.jquery.com/jquery-3.7.1.js

也可直接在jQuery官網下載最小的版本

  • 通過 jQuery AJAX 方法,您能夠使用 HTTP Get 和 HTTP Post 從遠程服務器上請求文本、HTML、XML 或 JSON – 同時您能夠把這些外部數據直接載入網頁的被選元素中

  • jQuery Ajax本質就是 XMLHttpRequest,對他進行了封裝,方便調用

jQuery.get(...)
/* 參數   
- url: 待載入頁面的URL地址
- data: 待發送 key/value 參數
- success: 載入成功時回調函數
- dataType: 返回內容格式, xml, json, script, text, html  */
jQuery.post(...)
/* 參數   
- url: 待載入頁面的URL地址
- data: 待發送 key/value 參數
- success: 載入成功時回調函數
- dataType: 返回內容格式, xml, json, script, text, html  */
jQuery.getJSON(...)
/* 參數   
- url: 待載入頁面的URL地址
- data: 待發送 key/value 參數
- success: 載入成功時回調函數  */
jQuery.getScript(...)
/* 參數   
- url: 待載入頁面的URL地址
- data: 待發送 key/value 參數
- success: 載入成功時回調函數  */
jQuery.ajax(...)
/* 參數(了解)
- url: 請求地址
- type: 請求方式,GET、POST(1.9.0之后用method)
- headers: 請求頭
- data: 要發送的數據
- contentType: 即將發送信息至服務器的內容編碼類型(默認: "application/x-www-form-urlencoded; charset=UTF-8")
- async: 是否異步
- timeout: 設置請求超時時間(毫秒)
- beforeSend: 發送請求前執行的函數(全局)
- complete: 完成之后執行的回調函數(全局)
- success: 成功之后執行的回調函數(全局)
- error: 失敗之后執行的回調函數(全局)
- accepts: 通過請求頭發送給服務器,告訴服務器當前客戶端可接受的數據類型
- dataType: 將服務器端返回的數據轉換成指定類型
- "xml": 將服務器端返回的內容轉換成xml格式
- "text": 將服務器端返回的內容轉換成普通文本格式
- "html": 將服務器端返回的內容轉換成普通文本格式,在插入DOM中時,如果包含JavaScript標簽,則會嘗試去執行。
- "script": 嘗試將返回值當作JavaScript去執行,然后再將服務器端返回的內容轉換成普通文本格式
- "json": 將服務器端返回的內容轉換成相應的JavaScript對象
- "jsonp": JSONP 格式使用 JSONP 形式調用函數時,如 "myurl?callback=?" jQuery 將自動替換 ? 為正確的函數名,以執行回調函數  */

我們來個簡單的測試,使用最原始的HttpServletResponse處理 , .最簡單 , 最通用

1、配置web.xml 和 springmvc的配置文件,復制上面案例的即可 【記得靜態資源過濾和注解驅動配置上】

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xmlns:context="http://www.springframework.org/schema/context"xmlns:mvc="http://www.springframework.org/schema/mvc"xsi:schemaLocation="http://www.springframework.org/schema/beanshttp://www.springframework.org/schema/beans/spring-beans.xsdhttp://www.springframework.org/schema/contexthttps://www.springframework.org/schema/context/spring-context.xsdhttp://www.springframework.org/schema/mvchttps://www.springframework.org/schema/mvc/spring-mvc.xsd">
?<!-- 自動掃描指定的包,下面所有注解類交給IOC容器管理 --><context:component-scan base-package="com.kuang.controller"/><mvc:default-servlet-handler /><mvc:annotation-driven />
?<!-- 視圖解析器 --><bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"id="internalResourceViewResolver"><!-- 前綴 --><property name="prefix" value="/WEB-INF/jsp/" /><!-- 后綴 --><property name="suffix" value=".jsp" /></bean>
</beans>

2、編寫一個AjaxController

@Controller
public class AjaxController {@RequestMapping("/a1")public void ajax1(String name , HttpServletResponse response) throws IOException {if ("admin".equals(name)){response.getWriter().print("true");}else{response.getWriter().print("false");}}
}

3、導入jquery , 可以使用在線的CDN , 也可以下載導入

<script src="https://code.jquery.com/jquery-3.1.1.min.js"></script>
<script src="${pageContext.request.contextPath}/statics/js/jquery-3.1.1.min.js"></script>

4、編寫index.jsp測試

<%@ page contentType="text/html;charset=UTF-8" language="java" %><html><head><title>$Title$</title><%--<script src="https://code.jquery.com/jquery-3.1.1.min.js"></script>--%><script src="${pageContext.request.contextPath}/statics/js/jquery-3.1.1.min.js"></script><script>function a1(){$.post({url:"${pageContext.request.contextPath}/a1",data:{'name':$("#txtName").val()},success:function (data,status) {alert(data);alert(status);}});}</script></head><body><%--onblur:失去焦點觸發事件--%>用戶名:<input type="text" id="txtName" οnblur="a1()"/></body></html>

5、啟動tomcat測試!打開瀏覽器的控制臺,當我們鼠標離開輸入框的時候,可以看到發出了一個ajax的請求!是后臺返回給我們的結果!測試成功!

Springmvc實現

實體類user

@Data
@AllArgsConstructor
@NoArgsConstructor
public class User {private String name;private int age;private String sex;
}

我們來獲取一個集合對象,展示到前端頁面

@RequestMapping("/a2")
public List<User> ajax2(){List<User> list = new ArrayList<User>();list.add(new User("秦疆1號",3,"男"));list.add(new User("秦疆2號",3,"男"));list.add(new User("秦疆3號",3,"男"));return list; //由于@RestController注解,將list轉成json格式返回
}

前端頁面

<%@ page contentType="text/html;charset=UTF-8" language="java" %><html><head><title>Title</title></head><body><input type="button" id="btn" value="獲取數據"/><table width="80%" align="center"><tr><td>姓名</td><td>年齡</td><td>性別</td></tr><tbody id="content"></tbody></table><script src="${pageContext.request.contextPath}/statics/js/jquery-3.1.1.min.js"></script><script>$(function () {$("#btn").click(function () {$.post("${pageContext.request.contextPath}/a2",function (data) {console.log(data)var html="";for (var i = 0; i <data.length ; i++) {html+= "<tr>" +"<td>" + data[i].name + "</td>" +"<td>" + data[i].age + "</td>" +"<td>" + data[i].sex + "</td>" +"</tr>"}$("#content").html(html);});})})</script></body></html>

成功實現了數據回顯!可以體會一下Ajax的好處!

注冊提示效果

我們再測試一個小Demo,思考一下我們平時注冊時候,輸入框后面的實時提示怎么做到的;如何優化

我們寫一個Controller

@RequestMapping("/a3")
public String ajax3(String name,String pwd){String msg = "";//模擬數據庫中存在數據if (name!=null){if ("admin".equals(name)){msg = "OK";}else {msg = "用戶名輸入錯誤";}}if (pwd!=null){if ("123456".equals(pwd)){msg = "OK";}else {msg = "密碼輸入有誤";}}return msg; //由于@RestController注解,將msg轉成json格式返回
}

前端頁面 login.jsp

<%@ page contentType="text/html;charset=UTF-8" language="java" %><html><head><title>ajax</title><script src="${pageContext.request.contextPath}/statics/js/jquery-3.1.1.min.js"></script><script>function a1(){$.post({url:"${pageContext.request.contextPath}/a3",data:{'name':$("#name").val()},success:function (data) {if (data.toString()=='OK'){$("#userInfo").css("color","green");}else {$("#userInfo").css("color","red");}$("#userInfo").html(data);}});}function a2(){$.post({url:"${pageContext.request.contextPath}/a3",data:{'pwd':$("#pwd").val()},success:function (data) {if (data.toString()=='OK'){$("#pwdInfo").css("color","green");}else {$("#pwdInfo").css("color","red");}$("#pwdInfo").html(data);}});}</script></head><body><p>用戶名:<input type="text" id="name" οnblur="a1()"/><span id="userInfo"></span></p><p>密碼:<input type="text" id="pwd" οnblur="a2()"/><span id="pwdInfo"></span></p></body></html>

【記得處理json亂碼問題】

測試一下效果,動態請求響應,局部刷新,就是如此!

圖片

獲取baidu接口Demo

<!DOCTYPE HTML>
<html><head><meta http-equiv="Content-Type" content="text/html; charset=utf-8"><title>JSONP百度搜索</title><style>#q{width: 500px;height: 30px;border:1px solid #ddd;line-height: 30px;display: block;margin: 0 auto;padding: 0 10px;font-size: 14px;}#ul{width: 520px;list-style: none;margin: 0 auto;padding: 0;border:1px solid #ddd;margin-top: -1px;display: none;}#ul li{line-height: 30px;padding: 0 10px;}#ul li:hover{background-color: #f60;color: #fff;}</style><script>// 2.步驟二// 定義demo函數 (分析接口、數據)function demo(data){var Ul = document.getElementById('ul');var html = '';// 如果搜索數據存在 把內容添加進去if (data.s.length) {// 隱藏掉的ul顯示出來Ul.style.display = 'block';// 搜索到的數據循環追加到li里for(var i = 0;i<data.s.length;i++){html += '<li>'+data.s[i]+'</li>';}// 循環的li寫入ulUl.innerHTML = html;}}// 1.步驟一window.onload = function(){// 獲取輸入框和ulvar Q = document.getElementById('q');var Ul = document.getElementById('ul');// 事件鼠標抬起時候Q.onkeyup = function(){// 如果輸入框不等于空if (this.value != '') {// ☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆JSONPz重點☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆// 創建標簽var script = document.createElement('script');//給定要跨域的地址 賦值給src//這里是要請求的跨域的地址 我寫的是百度搜索的跨域地址script.src = 'https://sp0.baidu.com/5a1Fazu8AA54nxGko9WTAnF6hhy/su?wd='+this.value+'&cb=demo';// 將組合好的帶src的script標簽追加到body里document.body.appendChild(script);}}}</script></head><body><input type="text" id="q" /><ul id="ul"></ul></body>
</html>

本文來自互聯網用戶投稿,該文觀點僅代表作者本人,不代表本站立場。本站僅提供信息存儲空間服務,不擁有所有權,不承擔相關法律責任。
如若轉載,請注明出處:http://www.pswp.cn/news/897401.shtml
繁體地址,請注明出處:http://hk.pswp.cn/news/897401.shtml
英文地址,請注明出處:http://en.pswp.cn/news/897401.shtml

如若內容造成侵權/違法違規/事實不符,請聯系多彩編程網進行投訴反饋email:809451989@qq.com,一經查實,立即刪除!

相關文章

玩轉ChatGPT:GPT 深入研究功能

一、寫在前面 民間總結&#xff1a; 理科看Claude 3.7 Sonnet 文科看DeepSeek-R1 那么&#xff0c;ChatGPT呢&#xff1f; 看Deep Research&#xff08;深入研究&#xff09;功能。 對于科研狗來說&#xff0c;在這個文章爆炸的時代&#xff0c;如何利用AI準確、高效地收…

RabbitMQ 2025/3/5

高性能異步通信組件。 同步調用 以支付為例&#xff1a; 可見容易發生雪崩。 異步調用 以支付為例&#xff1a; 支付服務當甩手掌柜了&#xff0c;不管后面的幾個服務的結果。只管庫庫發&#xff0c;后面那幾個服務想取的時候就取&#xff0c;因為消息代理里可以一直裝&#x…

Win10 訪問 Ubuntu 18 硬盤

目錄 方案一&#xff1a;使用Samba共享服務Ubuntu 18 端配置Windows 10 端訪問 方案二&#xff1a;使用 SSHFS&#xff08;需在 Windows 上安裝 SSH 客戶端&#xff09;Ubuntu 18 端配置Windows 10 端配置 方案三&#xff1a;使用 FTP 服務Ubuntu 18 端配置Windows 10 端訪問 方…

Android15使用FFmpeg解碼并播放MP4視頻完整示例

效果: 1.編譯FFmpeg庫: 下載FFmpeg-kit的源碼并編譯生成安裝平臺庫 2.復制生成的FFmpeg庫so文件與包含目錄到自己的Android下 如果沒有prebuiltLibs目錄,創建一個,然后復制 包含目錄只復制arm64-v8a下

Hadoop、Hive、Spark的關系

Part1&#xff1a;Hadoop、Hive、Spark關系概覽 1、MapReduce on Hadoop 和spark都是數據計算框架&#xff0c;一般認為spark的速度比MR快2-3倍。 2、mapreduce是數據計算的過程&#xff0c;map將一個任務分成多個小任務&#xff0c;reduce的部分將結果匯總之后返回。 3、HIv…

計算機網絡篇:基礎知識總結與基于長期主義的內容更新

基礎知識總結 和 MySQL 類似&#xff0c;我同樣花了一周左右的時間根據 csview 對計算機網絡部分的八股文進行了整理&#xff0c;主要的內容包括&#xff1a;概述、TCP 與 UDP、IP、HTTP&#xff0c;其中我個人認為最重要的是 TCP 這部分的內容。 在此做一篇目錄索引&#xf…

[密碼學實戰]Java實現國密TLSv1.3單向認證

一、代碼運行結果 1.1 運行環境 1.2 運行結果 1.3 項目架構 二、TLS 協議基礎與國密背景 2.1 TLS 協議的核心作用 TLS(Transport Layer Security) 是保障網絡通信安全的加密協議,位于 TCP/IP 協議棧的應用層和傳輸層之間,提供: ? 數據機密性:通過對稱加密算法(如 AE…

09 HarmonyOS NEXT 仿uv-ui Tag組件開發教程系列(三)

溫馨提示&#xff1a;本篇博客的詳細代碼已發布到 git : https://gitcode.com/nutpi/HarmonyosNext 可以下載運行哦&#xff01; 文章目錄 Tag組件實戰應用與最佳實踐1. 復雜場景應用1.1 標簽篩選系統 2. 性能優化實踐2.1 狀態管理優化2.2 渲染性能優化 3. 實用功能擴展3.1 拖拽…

clickhouse查詢效率低

《關于ClickHouse查詢效率低的探討》 在數據處理的世界里&#xff0c;數據庫扮演著至關重要的角色。ClickHouse是一款專為在線分析處理&#xff08;OLAP&#xff09;設計的列式存儲數據庫管理系統。它因其快速的數據寫入和查詢速度而聞名&#xff0c;尤其適合處理海量數據。如…

Linux系統基于ARM平臺的LVGL移植

軟硬件介紹&#xff1a;Ubuntu 20.04 ARM 和&#xff08;Cortex-A53架構&#xff09;開發板 基本原理 LVGL圖形庫是支持使用Linux系統的Framebuffer幀緩沖設備實現的&#xff0c;如果想要實現在ARM開發板上運行LVGL圖形庫&#xff0c;那么就需要把LVGL圖形庫提供的關于幀緩沖設…

【GPT入門】第14課 openai調用高德地圖案例實現多輪會話與多輪接口調用

【GPT入門】第14課 openai調用高德地圖案例實現多輪會話與多輪接口調用 1.使用openai調用高德地圖API概述2. 高德接口調用申請3.實現代碼(多個function調用,多輪對話)4.執行結果1.使用openai調用高德地圖API概述 任務描述:使用openai調用高德地圖API,實現用戶問地理有關的…

每日一題-----面試

一、什么是孤兒進程&#xff1f;什么是僵尸進程&#xff1f; 1.孤兒進程是指父進程在子進程結束之前就已經退出&#xff0c;導致子進程失去了父進程的管理和控制&#xff0c;成為了 “孤兒”。此時&#xff0c;這些子進程會被系統的 init 進程&#xff08;在 Linux 系統中&…

Python深度學習算法介紹

一、引言 深度學習是機器學習的一個重要分支&#xff0c;它通過構建多層神經網絡結構&#xff0c;自動從數據中學習特征表示&#xff0c;從而實現對復雜模式的識別和預測。Python作為一門強大的編程語言&#xff0c;憑借其簡潔易讀的語法和豐富的庫支持&#xff0c;成為深度學…

【Python】Django 中的算法應用與實現

Django 中的算法應用與實現 在 Django 開發中&#xff0c;算法的應用可以極大地擴展 Web 應用的功能和性能。從簡單的數據處理到復雜的機器學習模型&#xff0c;Django 都可以作為一個強大的后端框架來支持這些算法的實現。本文將介紹幾種常見的算法及其在 Django 中的使用方法…

旋轉編碼器原理與應用詳解:從結構到實戰 | 零基礎入門STM32第四十七步

主題內容教學目的/擴展視頻旋轉編碼器電路原理&#xff0c;跳線設置&#xff0c;結構分析。驅動程序與調用。熟悉電路和驅動程序。 師從洋桃電子&#xff0c;杜洋老師 &#x1f4d1;文章目錄 一、旋轉編碼器是什么&#xff1f;二、內部結構揭秘2.1 機械組件解剖2.2 核心部件說明…

如何禁止電腦中某個應用聯網

一、通過防火墻基礎設置&#xff08;快速操作&#xff09; 打開控制面板 在任務欄搜索框輸入“控制面板”并打開&#xff0c;將右上角“查看方式”切換為“大圖標”。 進入防火墻設置 點擊 Windows Defender防火墻 → 左側選擇 允許應用或功能通過Windows Defender防火墻。…

aws(學習筆記第三十二課) 深入使用cdk(API Gateway + event bridge)

文章目錄 aws(學習筆記第三十二課) 深入使用cdk學習內容&#xff1a;1. 使用aws API Gatewaylambda1.1. 以前的練習1.2. 使用cdk創建API Gateway lambda1.3. 確認cdk創建API Gateway lambda 2. 使用event bridge練習producer和consumer2.1. 代碼鏈接2.2. 開始練習2.3. 代碼部…

城市霓虹燈夜景拍照后期Lr調色教程,手機濾鏡PS+Lightroom預設下載!

調色教程 在城市霓虹燈夜景拍攝中&#xff0c;由于現場光線復雜等因素&#xff0c;照片可能無法完全呈現出當時的視覺感受。通過 Lr 調色&#xff0c;可以彌補拍攝時的不足。例如&#xff0c;運用基本調整面板中的曝光、對比度、陰影等工具&#xff0c;可以處理出畫面的整體明暗…

自然語言處理:文本分類

介紹 大家好&#xff0c;我這個熱衷于分享知識的博主又來啦&#xff01;之前我們一起深入探討了自然語言處理領域中非常重要的兩個方法&#xff1a;樸素貝葉斯和邏輯斯諦回歸。在探索的過程中&#xff0c;我們剖析了樸素貝葉斯如何基于概率原理和特征條件獨立假設&#xff0c;…

PDFMathTranslate安裝使用

PDF全文翻譯&#xff01;&#xff01;&#xff01;&#xff01; PDFMathTranslate安裝使用 它是個啥 PDFMathTranslate 可能是一個用于 PDF 文件的數學公式翻譯 工具。它可能包含以下功能&#xff1a; 提取 PDF 內的數學公式 將數學公式轉換成 LaTeX 代碼 翻譯數學公式的內…