JavaScript 实例
基础 JavaScript 实例
用JavaScript输出文本
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>菜鸟教程(runoob.com)</title>
</head>
<body>
<h1>我的第一个 Web 页面</h1>
<p>我的第一个段落。</p>
<script>
document.write(Date());
</script>
</body>
</html>用JavaScript改变HTML元素
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>菜鸟教程(runoob.com)</title>
</head>
<body>
<h1>我的第一个 Web 页面</h1>
<p id="demo">我的第一个段落。</p>
<script>
document.getElementById("demo").innerHTML="段落已修改。";
</script>
</body>
</html>一个外部JavaScript
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>菜鸟教程(runoob.com)</title>
</head>
<body>
<h1>我的 Web 页面</h1>
<p id="demo">一个段落。</p>
<button type="button" onclick="myFunction()">点击这里</button>
<p><b>注释:</b>myFunction 保存在名为 "myScript.js" 的外部文件中。</p>
<script src="myScript.js"></script>
</body>
</html>JavaScript 语句、注释和代码块
JavaScript 语句
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>菜鸟教程(runoob.com)</title>
</head>
<body>
<h1>我的 Web 页面</h1>
<p id="demo">一个段落。</p>
<div id="myDIV">一个 DIV。</div>
<script>
document.getElementById("demo").innerHTML="你好 Dolly";
document.getElementById("myDIV").innerHTML="你最近怎么样?";
</script>
</body>
</html>JavaScript 代码块
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>菜鸟教程(runoob.com)</title>
</head>
<body>
<h1>我的 Web 页面</h1>
<p id="myPar">我是一个段落。</p>
<div id="myDiv">我是一个div。</div>
<p>
<button type="button" onclick="myFunction()">点击这里</button>
</p>
<script>
function myFunction(){
document.getElementById("myPar").innerHTML="你好世界!";
document.getElementById("myDiv").innerHTML="你最近怎么样?";
}
</script>
<p>当您点击上面的按钮时,两个元素会改变。</p>
</body>
</html>JavaScript 单行注释
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>菜鸟教程(runoob.com)</title>
</head>
<body>
<h1 id="myH1"></h1>
<p id="myP"></p>
<script>
// 输出标题:
document.getElementById("myH1").innerHTML="Welcome to my Homepage";
// 输出段落:
document.getElementById("myP").innerHTML="This is my first paragraph.";
</script>
<p><b>注释:</b>注释不会被执行。</p>
</body>
</html>JavaScript 多行注释
<!DOCTYPE html>
<html>
<head>
<title>菜鸟教程测试实例</title>
<meta charset="utf-8">
</head>
<body>
<h1 id="myH1"></h1>
<p id="myP"></p>
<script>
/*
下面的这些代码会输出
一个标题和一个段落
并将代表主页的开始
*/
document.getElementById("myH1").innerHTML="欢迎来到菜鸟教程";
document.getElementById("myP").innerHTML="这是一个段落。";
</script>
<p><b>注释:</b>注释块不会被执行。</p>
</body>
</html>使用单行注释来防止执行
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>菜鸟教程(runoob.com)</title>
</head>
<body>
<h1 id="myH1"></h1>
<p id="myP"></p>
<script>
//document.getElementById("myH1").innerHTML="欢迎来到我的主页";
document.getElementById("myP").innerHTML="这是我的第一个段落。";
</script>
<p><strong>注意:</strong> 注释块不会被执行</p>
</body>
</html>使用多行注释来防止执行
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>菜鸟教程(runoob.com)</title>
</head>
<body>
<h1 id="myH1"></h1>
<p id="myP"></p>
<script>
/*
document.getElementById("myH1").innerHTML="欢迎来到我的主页";
document.getElementById("myP").innerHTML="这是我的第一个段落。";
*/
</script>
<p><strong>注意:</strong>注释块不会被执行。</p>
</body>
</html>JavaScript 变量
声明一个变量,为它赋值,然后显示出来
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>菜鸟教程(runoob.com)</title>
</head>
<body>
<script>
var firstname;
firstname="Hege";
document.write(firstname);
document.write("<br>");
firstname="Tove";
document.write(firstname);
</script>
<p>上面的脚本定义了一个变量,给变量分配一个值并显示,再次修改变量的值后,再次显示。
</p>
</body>
</html>JavaScript 条件语句 If ... Else
If 语句
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>菜鸟教程(runoob.com)</title>
</head>
<body>
<p>如果时间早于 20:00,会获得问候 "Good day"。</p>
<button onclick="myFunction()">点击这里</button>
<p id="demo"></p>
<script>
function myFunction(){
var x="";
var time=new Date().getHours();
if (time<20){
x="Good day";
}
document.getElementById("demo").innerHTML=x;
}
</script>
</body>
</html>If...else 语句
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>菜鸟教程(runoob.com)</title>
</head>
<body>
<p>点击这个按钮,获得基于时间的问候。</p>
<button onclick="myFunction()">点击这里</button>
<p id="demo"></p>
<script>
function myFunction(){
var x="";
var time=new Date().getHours();
if (time<20){
x="Good day";
}
else{
x="Good evening";
}
document.getElementById("demo").innerHTML=x;
}
</script>
</body>
</html>随机链接
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>菜鸟教程(runoob.com)</title>
</head>
<body>
<p id="demo"></p>
<script>
var r=Math.random();
var x=document.getElementById("demo")
if (r>0.5){
x.innerHTML="<a href='http://www.runoob.com'>访问菜鸟教程</a>";
}
else{
x.innerHTML="<a href='http://wwf.org'>Visit WWF</a>";
}
</script>
</body>
</html>Switch 语句
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>菜鸟教程(runoob.com)</title>
</head>
<body>
<p>点击下面的按钮来显示今天是周几:</p>
<button onclick="myFunction()">点击这里</button>
<p id="demo"></p>
<script>
function myFunction(){
var x;
var d=new Date().getDay();
switch (d){
case 0:x="今天是星期日";
break;
case 1:x="今天是星期一";
break;
case 2:x="今天是星期二";
break;
case 3:x="今天是星期三";
break;
case 4:x="今天是星期四";
break;
case 5:x="今天是星期五";
break;
case 6:x="今天是星期六";
break;
}
document.getElementById("demo").innerHTML=x;
}
</script>
</body>
</html>JavaScript 消息框
Alert(警告)框
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<script>
function myFunction(){
alert("你好,我是一个警告框!");
}
</script>
</head>
<body>
<input type="button" onclick="myFunction()" value="显示警告框" />
</body>
</html>带有换行的警告框
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>菜鸟教程(runoob.com)</title>
</head>
<body>
<p>点击按钮在弹窗总使用换行。</p>
<button onclick="myFunction()">点我</button>
<p id="demo"></p>
<script>
function myFunction(){
alert("Hello\nHow are you?");
}
</script>
</body>
</html>确认框
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>菜鸟教程(runoob.com)</title>
</head>
<body>
<p>点击按钮,显示确认框。</p>
<button onclick="myFunction()">点我</button>
<p id="demo"></p>
<script>
function myFunction(){
var x;
var r=confirm("按下按钮!");
if (r==true){
x="你按下了\"确定\"按钮!";
}
else{
x="你按下了\"取消\"按钮!";
}
document.getElementById("demo").innerHTML=x;
}
</script>
</body>
</html>提示框
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>菜鸟教程(runoob.com)</title>
</head>
<body>
<p>点击按钮查看输入的对话框。</p>
<button onclick="myFunction()">点我</button>
<p id="demo"></p>
<script>
function myFunction(){
var x;
var person=prompt("请输入你的名字","Harry Potter");
if (person!=null && person!=""){
x="你好 " + person + "! 今天感觉如何?";
document.getElementById("demo").innerHTML=x;
}
}
</script>
</body>
</html>JavaScript 函数
函数
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>菜鸟教程(runoob.com)</title>
<script>
function myFunction(){
alert("你好,世界!");
}
</script>
</head>
<body>
<button onclick="myFunction()">点我</button>
<p>当按钮点击后,一个函数将被执行,该函数结果警告一条信息。</p>
</body>
</html>带有参数的函数
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>菜鸟教程(runoob.com)</title>
</head>
<body>
<p>点击这个按钮,来调用带参数的函数。</p>
<button onclick="myFunction('Harry Potter','Wizard')">点击这里</button>
<script>
function myFunction(name,job){
alert("Welcome " + name + ", the " + job);
}
</script>
</body>
</html>带有参数的函数 2
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>菜鸟教程(runoob.com)</title>
<script>
function myfunction(txt) {
alert(txt);
}
</script>
</head>
<body>
<form>
<input type="button"
onclick="myfunction('Good Morning!')"
value="在早上">
<input type="button"
onclick="myfunction('Good Evening!')"
value="在晚上">
</form>
<p>
当你点击其中任意一个按钮,一个函数将被执行,函数结果弹出一个警告显示传递的参数。
</p>
</body>
</html>返回值的函数
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>菜鸟教程(runoob.com)</title>
<script>
function myFunction(){
return ("Hello world!");
}
</script>
</head>
<body>
<script>
document.write(myFunction())
</script>
</body>
</html>带有参数并返回值的函数
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>菜鸟教程(runoob.com)</title>
</head>
<body>
<p>本例调用的函数会执行一个计算,然后返回结果:</p>
<p id="demo"></p>
<script>
function myFunction(a,b){
return a*b;
}
document.getElementById("demo").innerHTML=myFunction(4,3);
</script>
</body>
</html>JavaScript 循环
For 循环
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>菜鸟教程(runoob.com)</title>
</head>
<body>
<p>单击按钮将代码块循环执行5次。</p>
<button onclick="myFunction()">点我</button>
<p id="demo"></p>
<script>
function myFunction(){
var x="",i;
for (i=0;i<5;i++){
x=x + "这个数字是" + i + "<br>";
}
document.getElementById("demo").innerHTML=x;
}
</script>
</body>
</html>循环输出 HTML 标题
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>菜鸟教程(runoob.com)</title>
</head>
<body>
<p>单击按钮将HTML标题设置从1到6的样式显示</p>
<button onclick="myFunction()">点我</button>
<div id="demo"></div>
<script>
function myFunction(){
var x="",i;
for (i=1; i<=6; i++){
x=x + "<h" + i + ">Heading " + i + "</h" + i + ">";
}
document.getElementById("demo").innerHTML=x;
}
</script>
</body>
</html>While 循环
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>菜鸟教程(runoob.com)</title>
</head>
<body>
<p>点击下面的按钮,只要 i 小于 5 就一直循环代码块。</p>
<button onclick="myFunction()">点击这里</button>
<p id="demo"></p>
<script>
function myFunction(){
var x="",i=0;
while (i<5){
x=x + "该数字为 " + i + "<br>";
i++;
}
document.getElementById("demo").innerHTML=x;
}
</script>
</body>
</html>Do while 循环
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>菜鸟教程(runoob.com)</title>
</head>
<body>
<p>点击下面的按钮,只要 i 小于 5 就一直循环代码块。</p>
<button onclick="myFunction()">点击这里</button>
<p id="demo"></p>
<script>
function myFunction(){
var x="",i=0;
do{
x=x + "该数字为 " + i + "<br>";
i++;
}
while (i<5)
document.getElementById("demo").innerHTML=x;
}
</script>
</body>
</html>break 语句
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>菜鸟教程(runoob.com)</title>
</head>
<body>
<p>点击按钮,测试带有 break 语句的循环。</p>
<button onclick="myFunction()">点击这里</button>
<p id="demo"></p>
<script>
function myFunction(){
var x="",i=0;
for (i=0;i<10;i++){
if (i==3){
break;
}
x=x + "该数字为 " + i + "<br>";
}
document.getElementById("demo").innerHTML=x;
}
</script>
</body>
</html>continue 语句
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>菜鸟教程(runoob.com)</title>
</head>
<body>
<p>点击下面的按钮来执行循环,该循环会跳过 i=3 的数字。</p>
<button onclick="myFunction()">点击这里</button>
<p id="demo"></p>
<script>
function myFunction(){
var x="",i=0;
for (i=0;i<10;i++){
if (i==3){
continue;
}
x=x + "该数字为 " + i + "<br>";
}
document.getElementById("demo").innerHTML=x;
}
</script>
</body>
</html>使用 For...In 声明来遍历数组内的元素
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>菜鸟教程(runoob.com)</title>
</head>
<body>
<p>点击下面的按钮,循环遍历对象 "person" 的属性。</p>
<button onclick="myFunction()">点击这里</button>
<p id="demo"></p>
<script>
function myFunction(){
var x;
var txt="";
var person={fname:"Bill",lname:"Gates",age:56};
for (x in person){
txt=txt + person[x];
}
document.getElementById("demo").innerHTML=txt;
}
</script>
</body>
</html>JavaScript 事件
onclick事件
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>菜鸟教程(runoob.com)</title>
<script>
function displayDate(){
document.getElementById("demo").innerHTML=Date();
}
</script>
</head>
<body>
<h1>我的第一个 JavaScript 程序</h1>
<p id="demo">这是一个段落</p>
<button type="button" onclick="displayDate()">显示日期</button>
</body>
</html>onmouseover 事件
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>菜鸟教程(runoob.com)</title>
<script>
function writeText(txt){
document.getElementById("desc").innerHTML=txt;
}
</script>
</head>
<body>
<img src ="planets.gif" width ="145" height ="126" alt="Planets" usemap="#planetmap" />
<map name="planetmap">
<area shape ="rect" coords ="0,0,82,126"
onmouseover="writeText('太阳和气体巨星类似木星是太阳系中最大的物体。')"
href ="sun.htm" target ="_blank" alt="Sun" />
<area shape ="circle" coords ="90,58,3"
onmouseover="writeText('从地球上很难研究水星,因为它太接近太阳。')"
href ="mercur.htm" target ="_blank" alt="Mercury" />
<area shape ="circle" coords ="124,58,8"
onmouseover="writeText('至到1960年,金星经常被认为是地球的孪生妹妹,因为金星是最靠近我们的行星,并且两个行星有很多相似的特点。')" t')"
href ="venus.htm" target ="_blank" alt="Venus" />
</map>
<p id="desc">鼠标在太阳和星星上移动,可以看到不同的描述。</p>
</body>
</html>JavaScript 错误处理
try...catch 语句
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>菜鸟教程(runoob.com)</title>
<script>
var txt="";
function message(){
try {
adddlert("Welcome guest!");
}
catch(err) {
txt="本页有一个错误。\n\n";
txt+="错误描述:" + err.message + "\n\n";
txt+="点击确定继续。\n\n";
alert(txt);
}
}
</script>
</head>
<body>
<input type="button" value="查看消息" onclick="message()" />
</body>
</html>带有确认框的 try...catch 语句
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>菜鸟教程(runoob.com)</title>
<script>
var txt="";
function message(){
try{
adddlert("Welcome guest!");
}
catch(err){
txt="本页有一个错误。\n\n";
txt+="单击确定继续跳转\n";
txt+="或者单击取消返回\n\n";
if(confirm(txt)){
document.location.href="//www.runoob.com/";
}
}
}
</script>
</head>
<body>
<input type="button" value="查看消息" onclick="message()" />
</body>
</html>onerror 事件
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>菜鸟教程(runoob.com)</title>
<script>
onerror=handleErr;
var txt="";
function handleErr(msg,url,l){
txt="该页面有一个错误\n\n";
txt+="错误: " + msg + "\n";
txt+="URL: " + url + "\n";
txt+="行: " + l + "\n\n";
txt+="点击确定继续。\n\n";
alert(txt);
return true;
}
function message(){
adddlert("Welcome guest!");
}
</script>
</head>
<body>
<input type="button" value="查看消息" onclick="message()" />
</body>
</html>高级 JavaScript 实例
创建一个欢迎 cookie
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>菜鸟教程(runoob.com)</title>
</head>
<head>
<script>
function setCookie(cname,cvalue,exdays){
var d = new Date();
d.setTime(d.getTime()+(exdays*24*60*60*1000));
var expires = "expires="+d.toGMTString();
document.cookie = cname+"="+cvalue+"; "+expires;
}
function getCookie(cname){
var name = cname + "=";
var ca = document.cookie.split(';');
for(var i=0; i<ca.length; i++) {
var c = ca[i].trim();
if (c.indexOf(name)==0) { return c.substring(name.length,c.length); }
}
return "";
}
function checkCookie(){
var user=getCookie("username");
if (user!=""){
alert("欢迎 " + user + " 再次访问");
}
else {
user = prompt("请输入你的名字:","");
if (user!="" && user!=null){
setCookie("username",user,30);
}
}
}
</script>
</head>
<body onload="checkCookie()"></body>
</html>简单的计时
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>菜鸟教程(runoob.com)</title>
</head>
<body>
<p>点击按钮,在等待 3 秒后弹出 "Hello"。</p>
<button onclick="myFunction()">点我</button>
<script>
function myFunction(){
setTimeout(function(){alert("Hello")},3000);
}
</script>
</body>
</html>另一个简单的计时
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>菜鸟教程(runoob.com)</title>
</head>
<head>
<script>
function timedText(){
var x=document.getElementById('txt');
var t1=setTimeout(function(){x.value="2 秒"},2000);
var t2=setTimeout(function(){x.value="4 秒"},4000);
var t3=setTimeout(function(){x.value="6 秒"},6000);
}
</script>
</head>
<body>
<form>
<input type="button" value="显示文本时间!" onclick="timedText()" />
<input type="text" id="txt" />
</form>
<p>点击上面的按钮,输出的文本将告诉你2秒,4秒,6秒已经过去了。</p>
</body>
</html>在一个无穷循环中的计时事件
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>菜鸟教程(runoob.com)</title>
<script>
var c=0;
var t;
var timer_is_on=0;
function timedCount(){
document.getElementById('txt').value=c;
c=c+1;
t=setTimeout("timedCount()",1000);
}
function doTimer(){
if (!timer_is_on)
{
timer_is_on=1;
timedCount();
}
}
</script>
</head>
<body>
<form>
<input type="button" value="开始计数!" onClick="doTimer()">
<input type="text" id="txt">
</form>
<p>单击按钮,输入框将从0开始一直计数。</p>
</body>
</html>带有停止按钮的无穷循环中的计时事件
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>菜鸟教程(runoob.com)</title>
<script>
var c=0;
var t;
var timer_is_on=0;
function timedCount(){
document.getElementById('txt').value=c;
c=c+1;
t=setTimeout(function(){timedCount()},1000);
}
function doTimer(){
if (!timer_is_on){
timer_is_on=1;
timedCount();
}
}
function stopCount(){
clearTimeout(t);
timer_is_on=0;
}
</script>
</head>
<body>
<form>
<input type="button" value="开始计数!" onclick="doTimer()" />
<input type="text" id="txt" />
<input type="button" value="停止计数!" onclick="stopCount()" />
</form>
<p>
单击开始计数按钮,按下时开始计数,输入框将从0开始一直计数。单击停止计数按钮,按下时停止计数,再次点击开始计数按钮,又再次开始计数。
</p>
</body>
</html>使用计时事件制作的钟表
- 创建对象的实例
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>菜鸟教程(runoob.com)</title>
</head>
<body>
<script>
person={firstname:"John",lastname:"Doe",age:50,eyecolor:"blue"}
document.write(person.firstname + " is " + person.age + " years old.");
</script>
</body>
</html>创建用于对象的模板
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>菜鸟教程(runoob.com)</title>
</head>
<body>
<script>
function person(firstname,lastname,age,eyecolor){
this.firstname=firstname;
this.lastname=lastname;
this.age=age;
this.eyecolor=eyecolor;
}
myFather=new person("John","Doe",50,"blue");
document.write(myFather.firstname + " is " + myFather.age + " years old.");
</script>
</body>
</html>JavaScript 应用实例
javascript 幻灯片代码(含自动播放)
HTML代码部分
<div class="slideshow-container">
<div class="mySlides fade">
<div class="numbertext">1 / 3</div>
<img src="img1.jpg" style="width:100%">
<div class="text">文本 1</div>
</div>
<div class="mySlides fade">
<div class="numbertext">2 / 3</div>
<img src="img2.jpg" style="width:100%">
<div class="text">文本 2</div>
</div>
<div class="mySlides fade">
<div class="numbertext">3 / 3</div>
<img src="img3.jpg" style="width:100%">
<div class="text">文本 3</div>
</div>
<a class="prev" onclick="plusSlides(-1)">❮</a>
<a class="next" onclick="plusSlides(1)">❯</a>
</div>
<br>
<div style="text-align:center">
<span class="dot" onclick="currentSlide(1)"></span>
<span class="dot" onclick="currentSlide(2)"></span>
<span class="dot" onclick="currentSlide(3)"></span>
</div> CSS 代码设置上一张下一张图片的按钮及文本。
CSS 代码
* {box-sizing:border-box}
body {font-family: Verdana,sans-serif;}
.mySlides {display:none}
/* 幻灯片容器 */
.slideshow-container {
max-width: 1000px;
position: relative;
margin: auto;
}
/* 下一张 & 上一张 按钮 */
.prev, .next {
cursor: pointer;
position: absolute;
top: 50%;
width: auto;
margin-top: -22px;
padding: 16px;
color: white;
font-weight: bold;
font-size: 18px;
transition: 0.6s ease;
border-radius: 0 3px 3px 0;
}
/* 定位 "下一张" 按钮靠右 */
.next {
right: 0;
border-radius: 3px 0 0 3px;
}
/* On hover, add a black background color with a little bit see-through */
.prev:hover, .next:hover {
background-color: rgba(0,0,0,0.8);
}
/* 标题文本 */
.text {
color: #f2f2f2;
font-size: 15px;
padding: 8px 12px;
position: absolute;
bottom: 8px;
width: 100%;
text-align: center;
}
/* 数字文本 (1/3 等) */
.numbertext {
color: #f2f2f2;
font-size: 12px;
padding: 8px 12px;
position: absolute;
top: 0;
}
/* 标记符号 */
.dot {
cursor:pointer;
height: 13px;
width: 13px;
margin: 0 2px;
background-color: #bbb;
border-radius: 50%;
display: inline-block;
transition: background-color 0.6s ease;
}
.active, .dot:hover {
background-color: #717171;
}
/* 淡出动画 */
.fade {
-webkit-animation-name: fade;
-webkit-animation-duration: 1.5s;
animation-name: fade;
animation-duration: 1.5s;
}
@-webkit-keyframes fade {
from {opacity: .4}
to {opacity: 1}
}
@keyframes fade {
from {opacity: .4}
to {opacity: 1}
}JavaScript 代码
var slideIndex = 1;
showSlides(slideIndex);
function plusSlides(n) {
showSlides(slideIndex += n);
}
function currentSlide(n) {
showSlides(slideIndex = n);
}
function showSlides(n) {
var i;
var slides = document.getElementsByClassName("mySlides");
var dots = document.getElementsByClassName("dot");
if (n > slides.length) {slideIndex = 1}
if (n < 1) {slideIndex = slides.length}
for (i = 0; i < slides.length; i++) {
slides[i].style.display = "none";
}
for (i = 0; i < dots.length; i++) {
dots[i].className = dots[i].className.replace(" active", "");
}
slides[slideIndex-1].style.display = "block";
dots[slideIndex-1].className += " active";
}- CSS 日历样式
以下是一个简单的 CSS 日历代码:
HTML 代码
<h1>CSS 日历</h1>
<div class="month">
<ul>
<li class="prev">❮</li>
<li class="next">❯</li>
<li style="text-align:center">
August<br>
<span style="font-size:18px">2016</span>
</li>
</ul>
</div>
<ul class="weekdays">
<li>Mo</li>
<li>Tu</li>
<li>We</li>
<li>Th</li>
<li>Fr</li>
<li>Sa</li>
<li>Su</li>
</ul>
<ul class="days">
<li>1</li>
<li>2</li>
<li>3</li>
<li>4</li>
<li>5</li>
<li>6</li>
<li>7</li>
<li>8</li>
<li>9</li>
<li><span class="active">10</span></li>
<li>11</li>
<li>12</li>
<li>13</li>
<li>14</li>
<li>15</li>
<li>16</li>
<li>17</li>
<li>18</li>
<li>19</li>
<li>20</li>
<li>21</li>
<li>22</li>
<li>23</li>
<li>24</li>
<li>25</li>
<li>26</li>
<li>27</li>
<li>28</li>
<li>29</li>
<li>30</li>
<li>31</li>
</ul>CSS 代码
* {box-sizing:border-box;}
ul {list-style-type: none;}
body {font-family: Verdana,sans-serif;}
.month {
padding: 70px 25px;
width: 100%;
background: #1abc9c;
}
.month ul {
margin: 0;
padding: 0;
}
.month ul li {
color: white;
font-size: 20px;
text-transform: uppercase;
letter-spacing: 3px;
}
.month .prev {
float: left;
padding-top: 10px;
}
.month .next {
float: right;
padding-top: 10px;
}
.weekdays {
margin: 0;
padding: 10px 0;
background-color: #ddd;
}
.weekdays li {
display: inline-block;
width: 13.6%;
color: #666;
text-align: center;
}
.days {
padding: 10px 0;
background: #eee;
margin: 0;
}
.days li {
list-style-type: none;
display: inline-block;
width: 13.6%;
text-align: center;
margin-bottom: 5px;
font-size:12px;
color: #777;
}
.days li .active {
padding: 5px;
background: #1abc9c;
color: white !important
}
/* 添加不同尺寸屏幕的样式 */
@media screen and (max-width:720px) {
.weekdays li, .days li {width: 13.1%;}
}
@media screen and (max-width: 420px) {
.weekdays li, .days li {width: 12.5%;}
.days li .active {padding: 2px;}
}
@media screen and (max-width: 290px) {
.weekdays li, .days li {width: 12.2%;}
}JavaScript 弹窗
以下是一个简单的 JavaScript 弹窗代码实例。
HTML 代码
<!-- 打开弹窗按钮 -->
<button id="myBtn">打开弹窗</button>
<!-- 弹窗 -->
<div id="myModal" class="modal">
<!-- 弹窗内容 -->
<div class="modal-content">
<span class="close">×</span>
<p>弹窗中的文本...</p>
</div>
</div> CSS 代码
/* 弹窗 (background) */
.modal {
display: none; /* 默认隐藏 */
position: fixed; /* 固定定位 */
z-index: 1; /* 设置在顶层 */
left: 0;
top: 0;
width: 100%;
height: 100%;
overflow: auto;
background-color: rgb(0,0,0);
background-color: rgba(0,0,0,0.4);
}
/* 弹窗内容 */
.modal-content {
background-color: #fefefe;
margin: 15% auto;
padding: 20px;
border: 1px solid #888;
width: 80%;
}
/* 关闭按钮 */
.close {
color: #aaa;
float: right;
font-size: 28px;
font-weight: bold;
}
.close:hover,
.close:focus {
color: black;
text-decoration: none;
cursor: pointer;
}JavaScript 代码
// 获取弹窗
var modal = document.getElementById('myModal');
// 打开弹窗的按钮对象
var btn = document.getElementById("myBtn");
// 获取 <span> 元素,用于关闭弹窗
var span = document.querySelector('.close');
// 点击按钮打开弹窗
btn.onclick = function() {
modal.style.display = "block";
}
// 点击 <span> (x), 关闭弹窗
span.onclick = function() {
modal.style.display = "none";
}
// 在用户点击其他地方时,关闭弹窗
window.onclick = function(event) {
if (event.target == modal) {
modal.style.display = "none";
}
}弹窗添加头部和底部
HTML 代码
<!-- 打开弹窗按钮 -->
<button id="myBtn">打开弹窗</button>
<!-- 弹窗 -->
<div id="myModal" class="modal">
<!-- 弹窗内容 -->
<div class="modal-content">
<div class="modal-header">
<span class="close">×</span>
<h2>弹窗头部</h2>
</div>
<div class="modal-body">
<p>弹窗文本...</p>
<p>弹窗文本...</p>
</div>
<div class="modal-footer">
<h3>弹窗底部</h3>
</div>
</div>
</div>CSS 代码
/* 弹窗 (background) */
.modal {
display: none; /* 默认隐藏 */
position: fixed;
z-index: 1;
padding-top: 100px;
left: 0;
top: 0;
width: 100%;
height: 100%;
overflow: auto;
background-color: rgb(0,0,0);
background-color: rgba(0,0,0,0.4);
}
/* 弹窗内容 */
.modal-content {
position: relative;
background-color: #fefefe;
margin: auto;
padding: 0;
border: 1px solid #888;
width: 80%;
box-shadow: 0 4px 8px 0 rgba(0,0,0,0.2),0 6px 20px 0 rgba(0,0,0,0.19);
-webkit-animation-name: animatetop;
-webkit-animation-duration: 0.4s;
animation-name: animatetop;
animation-duration: 0.4s
}
/* 添加动画 */
@-webkit-keyframes animatetop {
from {top:-300px; opacity:0}
to {top:0; opacity:1}
}
@keyframes animatetop {
from {top:-300px; opacity:0}
to {top:0; opacity:1}
}
/* 关闭按钮 */
.close {
color: white;
float: right;
font-size: 28px;
font-weight: bold;
}
.close:hover,
.close:focus {
color: #000;
text-decoration: none;
cursor: pointer;
}
.modal-header {
padding: 2px 16px;
background-color: #5cb85c;
color: white;
}
.modal-body {padding: 2px 16px;}
.modal-footer {
padding: 2px 16px;
background-color: #5cb85c;
color: white;
}JavaScript 图片弹窗
本文我们为大家介绍如何使用 JavaScript 与 CSS 来创建图片弹窗。
HTML 代码
<!-- 触发弹窗 - 图片改为你的图片地址 -->
<img id="myImg" src="img.jpg" alt="文本描述信息" width="300" height="200">
<!-- 弹窗 -->
<div id="myModal" class="modal">
<!-- 关闭按钮 -->
<span class="close" onclick="document.getElementById('myModal').style.display='none'">×</span>
<!-- 弹窗内容 -->
<img class="modal-content" id="img01">
<!-- 文本描述 -->
<div id="caption"></div>
</div>CSS 代码
/* 触发弹窗图片的样式 */
#myImg {
border-radius: 5px;
cursor: pointer;
transition: 0.3s;
}
#myImg:hover {opacity: 0.7;}
/* 弹窗背景 */
.modal {
display: none; /* Hidden by default */
position: fixed; /* Stay in place */
z-index: 1; /* Sit on top */
padding-top: 100px; /* Location of the box */
left: 0;
top: 0;
width: 100%; /* Full width */
height: 100%; /* Full height */
overflow: auto; /* Enable scroll if needed */
background-color: rgb(0,0,0); /* Fallback color */
background-color: rgba(0,0,0,0.9); /* Black w/ opacity */
}
/* 图片 */
.modal-content {
margin: auto;
display: block;
width: 80%;
max-width: 700px;
}
/* 文本内容 */
#caption {
margin: auto;
display: block;
width: 80%;
max-width: 700px;
text-align: center;
color: #ccc;
padding: 10px 0;
height: 150px;
}
/* 添加动画 */
.modal-content, #caption {
-webkit-animation-name: zoom;
-webkit-animation-duration: 0.6s;
animation-name: zoom;
animation-duration: 0.6s;
}
@-webkit-keyframes zoom {
from {-webkit-transform:scale(0)}
to {-webkit-transform:scale(1)}
}
@keyframes zoom {
from {transform:scale(0)}
to {transform:scale(1)}
}
/* 关闭按钮 */
.close {
position: absolute;
top: 15px;
right: 35px;
color: #f1f1f1;
font-size: 40px;
font-weight: bold;
transition: 0.3s;
}
.close:hover,
.close:focus {
color: #bbb;
text-decoration: none;
cursor: pointer;
}
/* 小屏幕中图片宽度为 100% */
@media only screen and (max-width: 700px){
.modal-content {
width: 100%;
}
} JavaScript 代码
// 获取弹窗
var modal = document.getElementById('myModal');
// 获取图片插入到弹窗 - 使用 "alt" 属性作为文本部分的内容
var img = document.getElementById('myImg');
var modalImg = document.getElementById("img01");
var captionText = document.getElementById("caption");
img.onclick = function(){
modal.style.display = "block";
modalImg.src = this.src;
captionText.innerHTML = this.alt;
}
// 获取 <span> 元素,设置关闭按钮
var span = document.getElementsByClassName("close")[0];
// 当点击 (x), 关闭弹窗
span.onclick = function() {
modal.style.display = "none";
}JavaScript Lightbox
本文我们为大家介绍如何使用 HTML、JavaScript 与 CSS 来创建 Lightbox,类似相册预览功能。
HTML 代码
<!-- 图片改为你的图片地址 -->
<h2 style="text-align:center">Lightbox</h2>
<div class="row">
<div class="column">
<img src="http://static.runoob.com/images/demo/demo1.jpg" style="width:100%" onclick="openModal();currentSlide(1)" class="hover-shadow cursor">
</div>
<div class="column">
<img src="http://static.runoob.com/images/demo/demo2.jpg" style="width:100%" onclick="openModal();currentSlide(2)" class="hover-shadow cursor">
</div>
<div class="column">
<img src="http://static.runoob.com/images/demo/demo3.jpg" style="width:100%" onclick="openModal();currentSlide(3)" class="hover-shadow cursor">
</div>
<div class="column">
<img src="http://static.runoob.com/images/demo/demo4.jpg" style="width:100%" onclick="openModal();currentSlide(4)" class="hover-shadow cursor">
</div>
</div>
<div id="myModal" class="modal">
<span class="close cursor" onclick="closeModal()">×</span>
<div class="modal-content">
<div class="mySlides">
<div class="numbertext">1 / 4</div>
<img src="http://static.runoob.com/images/demo/demo1.jpg" style="width:100%">
</div>
<div class="mySlides">
<div class="numbertext">2 / 4</div>
<img src="http://static.runoob.com/images/demo/demo2.jpg" style="width:100%">
</div>
<div class="mySlides">
<div class="numbertext">3 / 4</div>
<img src="http://static.runoob.com/images/demo/demo3.jpg" style="width:100%">
</div>
<div class="mySlides">
<div class="numbertext">4 / 4</div>
<img src="http://static.runoob.com/images/demo/demo4.jpg" style="width:100%">
</div>
<a class="prev" onclick="plusSlides(-1)">❮</a>
<a class="next" onclick="plusSlides(1)">❯</a>
<div class="caption-container">
<p id="caption"></p>
</div>
<div class="column">
<img class="demo cursor" src="http://static.runoob.com/images/demo/demo1.jpg" style="width:100%" onclick="currentSlide(1)" alt="Nature and sunrise">
</div>
<div class="column">
<img class="demo cursor" src="http://static.runoob.com/images/demo/demo2.jpg" style="width:100%" onclick="currentSlide(2)" alt="Trolltunga, Norway">
</div>
<div class="column">
<img class="demo cursor" src="http://static.runoob.com/images/demo/demo3.jpg" style="width:100%" onclick="currentSlide(3)" alt="Mountains and fjords">
</div>
<div class="column">
<img class="demo cursor" src="http://static.runoob.com/images/demo/demo4.jpg" style="width:100%" onclick="currentSlide(4)" alt="Northern Lights">
</div>
</div>
</div>CSS 代码
body {
font-family: Verdana, sans-serif;
margin: 0;
}
* {
box-sizing: border-box;
}
.row > .column {
padding: 0 8px;
}
.row:after {
content: "";
display: table;
clear: both;
}
.column {
float: left;
width: 25%;
}
/* 弹窗背景 */
.modal {
display: none;
position: fixed;
z-index: 1;
padding-top: 100px;
left: 0;
top: 0;
width: 100%;
height: 100%;
overflow: auto;
background-color: black;
}
/* 弹窗内容 */
.modal-content {
position: relative;
background-color: #fefefe;
margin: auto;
padding: 0;
width: 90%;
max-width: 1200px;
}
/* 关闭按钮 */
.close {
color: white;
position: absolute;
top: 10px;
right: 25px;
font-size: 35px;
font-weight: bold;
}
.close:hover,
.close:focus {
color: #999;
text-decoration: none;
cursor: pointer;
}
.mySlides {
display: none;
}
.cursor {
cursor: pointer
}
/* 上一页 & 下一页 按钮 */
.prev,
.next {
cursor: pointer;
position: absolute;
top: 50%;
width: auto;
padding: 16px;
margin-top: -50px;
color: white;
font-weight: bold;
font-size: 20px;
transition: 0.6s ease;
border-radius: 0 3px 3px 0;
user-select: none;
-webkit-user-select: none;
}
/* 定位下一页按钮到右侧 */
.next {
right: 0;
border-radius: 3px 0 0 3px;
}
/* 鼠标移动上去修改背景色为黑色 */
.prev:hover,
.next:hover {
background-color: rgba(0, 0, 0, 0.8);
}
/* 页数(1/3 etc) */
.numbertext {
color: #f2f2f2;
font-size: 12px;
padding: 8px 12px;
position: absolute;
top: 0;
}
img {
margin-bottom: -4px;
}
.caption-container {
text-align: center;
background-color: black;
padding: 2px 16px;
color: white;
}
.demo {
opacity: 0.6;
}
.active,
.demo:hover {
opacity: 1;
}
img.hover-shadow {
transition: 0.3s
}
.hover-shadow:hover {
box-shadow: 0 4px 8px 0 rgba(0, 0, 0, 0.2), 0 6px 20px 0 rgba(0, 0, 0, 0.19)
}JavaScript 代码
function openModal() {
document.getElementById('myModal').style.display = "block";
}
function closeModal() {
document.getElementById('myModal').style.display = "none";
}
var slideIndex = 1;
showSlides(slideIndex);
function plusSlides(n) {
showSlides(slideIndex += n);
}
function currentSlide(n) {
showSlides(slideIndex = n);
}
function showSlides(n) {
var i;
var slides = document.getElementsByClassName("mySlides");
var dots = document.getElementsByClassName("demo");
var captionText = document.getElementById("caption");
if (n > slides.length) {slideIndex = 1}
if (n < 1) {slideIndex = slides.length}
for (i = 0; i < slides.length; i++) {
slides[i].style.display = "none";
}
for (i = 0; i < dots.length; i++) {
dots[i].className = dots[i].className.replace(" active", "");
}
slides[slideIndex-1].style.display = "block";
dots[slideIndex-1].className += " active";
captionText.innerHTML = dots[slideIndex-1].alt;
}javascript 搜索框自动提示
本文为大家介绍如何实现一个搜索框的提示功能,类似百度搜索。
HTML 代码
<input type="text" id="myInput" onkeyup="myFunction()" placeholder="搜索...">
<ul id="myUL">
<li><a href="#" class="header">A</a></li>
<li><a href="#">Adele</a></li>
<li><a href="#">Agnes</a></li>
<li><a href="#" class="header">B</a></li>
<li><a href="#">Billy</a></li>
<li><a href="#">Bob</a></li>
<li><a href="#" class="header">C</a></li>
<li><a href="#">Calvin</a></li>
<li><a href="#">Christina</a></li>
<li><a href="#">Cindy</a></li>
</ul> CSS 代码
#myInput {
background-image: url('https://static.runoob.com/images/mix/searchicon.png'); /* 搜索按钮 */
background-position: 10px 12px; /* 定位搜索按钮 */
background-repeat: no-repeat; /* 不重复图片*/
width: 100%;
font-size: 16px; /* 加大字体 */
padding: 12px 20px 12px 40px;
border: 1px solid #ddd;
margin-bottom: 12px;
}
#myUL {
/* 移除默认的列表样式 */
list-style-type: none;
padding: 0;
margin: 0;
}
#myUL li a {
border: 1px solid #ddd; /* 链接添加边框 */
margin-top: -1px;
background-color: #f6f6f6;
padding: 12px;
text-decoration: none;
font-size: 18px;
color: black;
display: block;
}
#myUL li a.header {
background-color: #e2e2e2;
cursor: default;
}
#myUL li a:hover:not(.header) {
background-color: #eee;
}JavaScript 代码
function myFunction() {
// 声明变量
var input, filter, ul, li, a, i;
input = document.getElementById('myInput');
filter = input.value.toUpperCase();
ul = document.getElementById("myUL");
li = ul.getElementsByTagName('li');
// 循环所有列表,查找匹配项
for (i = 0; i < li.length; i++) {
a = li[i].getElementsByTagName("a")[0];
if (a.innerHTML.toUpperCase().indexOf(filter) > -1) {
li[i].style.display = "";
} else {
li[i].style.display = "none";
}
}
}JavaScript 表格数据搜索
本文为大家介绍如何实现一个表格数据搜索的功能。
HTML 代码
<input type="text" id="myInput" onkeyup="myFunction()" placeholder="搜索...">
<table id="myTable">
<tr class="header">
<th style="width:60%;">名称</th>
<th style="width:40%;">城市</th>
</tr>
<tr>
<td>Alfreds Futterkiste</td>
<td>Germany</td>
</tr>
<tr>
<td>Berglunds snabbkop</td>
<td>Sweden</td>
</tr>
<tr>
<td>Island Trading</td>
<td>UK</td>
</tr>
<tr>
<td>Koniglich Essen</td>
<td>Germany</td>
</tr>
</table> CSS 代码
#myInput {
background-image: url('https://static.runoob.com/images/mix/searchicon.png'); /* 搜索按钮 */
background-position: 10px 12px; /* 定位搜索按钮 */
background-repeat: no-repeat; /* 不重复图片 */
width: 100%;
font-size: 16px;
padding: 12px 20px 12px 40px;
border: 1px solid #ddd;
margin-bottom: 12px;
}
#myTable {
border-collapse: collapse;
width: 100%;
border: 1px solid #ddd;
font-size: 18px;
}
#myTable th, #myTable td {
text-align: left;
padding: 12px;
}
#myTable tr {
/* 表格添加边框 */
border-bottom: 1px solid #ddd;
}
#myTable tr.header, #myTable tr:hover {
/* 表头及鼠标移动过 tr 时添加背景 */
background-color: #f1f1f1;
}JavaScript 代码
function myFunction() {
// 声明变量
var input, filter, table, tr, td, i;
input = document.getElementById("myInput");
filter = input.value.toUpperCase();
table = document.getElementById("myTable");
tr = table.getElementsByTagName("tr");
// 循环表格每一行,查找匹配项
for (i = 0; i < tr.length; i++) {
td = tr[i].getElementsByTagName("td")[0];
if (td) {
if (td.innerHTML.toUpperCase().indexOf(filter) > -1) {
tr[i].style.display = "";
} else {
tr[i].style.display = "none";
}
}
}
}JavaScript 实现列表按字母排序
HTML代码
<p>点击按钮按字母列表排序:</p>
<button onclick="sortList()">排序</button>
<ul id="id01">
<li>Oslo</li>
<li>Stockholm</li>
<li>Helsinki</li>
<li>Berlin</li>
<li>Rome</li>
<li>Madrid</li>
</ul>JavaScript代码
function sortList() {
var list, i, switching, b, shouldSwitch;
list = document.getElementById("id01");
switching = true;
/*Make a loop that will continue until
no switching has been done:*/
while (switching) {
//start by saying: no switching is done:
switching = false;
b = list.getElementsByTagName("LI");
//Loop through all list items:
for (i = 0; i < (b.length - 1); i++) {
//start by saying there should be no switching:
shouldSwitch = false;
/*check if the next item should
switch place with the current item:*/
if (b[i].innerHTML.toLowerCase() > b[i + 1].innerHTML.toLowerCase()) {
/*if next item is alphabetically lower than current item,
mark as a switch and break the loop:*/
shouldSwitch= true;
break;
}
}
if (shouldSwitch) {
/*If a switch has been marked, make the switch
and mark the switch as done:*/
b[i].parentNode.insertBefore(b[i + 1], b[i]);
switching = true;
}
}
}JavaScript 实现表格单列按字母排序
HTML代码
<p>点击按钮,表格 name 字段按字母排序:</p>
<p><button onclick="sortTable()">排序</button></p>
<table border="1" id="myTable">
<tr>
<th>Name</th>
<th>Country</th>
</tr>
<tr>
<td>Berglunds snabbkop</td>
<td>Sweden</td>
</tr>
<tr>
<td>North/South</td>
<td>UK</td>
</tr>
<tr>
<td>Alfreds Futterkiste</td>
<td>Germany</td>
</tr>
<tr>
<td>Koniglich Essen</td>
<td>Germany</td>
</tr>
<tr>
<td>Magazzini Alimentari Riuniti</td>
<td>Italy</td>
</tr>
<tr>
<td>Paris specialites</td>
<td>France</td>
</tr>
<tr>
<td>Island Trading</td>
<td>UK</td>
</tr>
<tr>
<td>Laughing Bacchus Winecellars</td>
<td>Canada</td>
</tr>
</table>JavaScript代码
function sortTable() {
var table, rows, switching, i, x, y, shouldSwitch;
table = document.getElementById("myTable");
switching = true;
/*Make a loop that will continue until
no switching has been done:*/
while (switching) {
//start by saying: no switching is done:
switching = false;
rows = table.getElementsByTagName("TR");
/*Loop through all table rows (except the
first, which contains table headers):*/
for (i = 1; i < (rows.length - 1); i++) {
//start by saying there should be no switching:
shouldSwitch = false;
/*Get the two elements you want to compare,
one from current row and one from the next:*/
x = rows[i].getElementsByTagName("TD")[0];
y = rows[i + 1].getElementsByTagName("TD")[0];
//check if the two rows should switch place:
if (x.innerHTML.toLowerCase() > y.innerHTML.toLowerCase()) {
//if so, mark as a switch and break the loop:
shouldSwitch= true;
break;
}
}
if (shouldSwitch) {
/*If a switch has been marked, make the switch
and mark that a switch has been done:*/
rows[i].parentNode.insertBefore(rows[i + 1], rows[i]);
switching = true;
}
}
}JavaScript 动画应用实例
HTML代码
<p>
<button onclick="myMove()">点我</button>
</p>
<div id ="myContainer">
<div id ="myAnimation"></div>
</div>JavaScript代码
function myMove() {
var elem = document.getElementById("myAnimation");
var pos = 0;
var id = setInterval(frame, 10);
function frame() {
if (pos == 350) {
clearInterval(id);
} else {
pos++;
elem.style.top = pos + 'px';
elem.style.left = pos + 'px';
}
}
}JavaScript 进度条实例
HTML代码
<h1>JavaScript 进度条</h1>
<div id="myProgress">
<div id="myBar"></div>
</div>
<br>
<button onclick="move()">点我</button>JavaScript代码
function move() {
var elem = document.getElementById("myBar");
var width = 1;
var id = setInterval(frame, 10);
function frame() {
if (width >= 100) {
clearInterval(id);
} else {
width++;
elem.style.width = width + '%';
}
}
}JavaScript 百分比进度条
HTML代码
<h1>JavaScript 百分比进度条</h1>
<div id="myProgress">
<div id="myBar">10%</div>
</div>
<br>
<button onclick="move()">点我</button>JavaScript代码
function move() {
var elem = document.getElementById("myBar");
var width = 10;
var id = setInterval(frame, 10);
function frame() {
if (width >= 100) {
clearInterval(id);
} else {
width++;
elem.style.width = width + '%';
elem.innerHTML = width * 1 + '%';
}
}
}JavaScript/CSS 实现提示弹窗
HTML代码
<body style="text-align:center">
<h2>弹窗</h2>
<div class="popup" onclick="myFunction()">点我有弹窗!
<span class="popuptext" id="myPopup">提示信息!</span>
</div>
</body>JavaScript代码
function myFunction() {
var popup = document.getElementById("myPopup");
popup.classList.toggle("show");
}JavaScript/CSS 实现待办事项列表(To Do List)
HTML代码
<div id="myDIV" class="header">
<h2 style="margin:5px">My To Do List</h2>
<input type="text" id="myInput" placeholder="Title...">
<span onclick="newElement()" class="addBtn">Add</span>
</div>
<ul id="myUL">
<li>Hit the gym</li>
<li class="checked">Pay bills</li>
<li>Meet George</li>
<li>Buy eggs</li>
<li>Read a book</li>
<li>Organize office</li>
</ul>JavaScript代码
// Create a "close" button and append it to each list item
var myNodelist = document.getElementsByTagName("LI");
var i;
for (i = 0; i < myNodelist.length; i++) {
var span = document.createElement("SPAN");
var txt = document.createTextNode("\u00D7");
span.className = "close";
span.appendChild(txt);
myNodelist[i].appendChild(span);
}
// Click on a close button to hide the current list item
var close = document.getElementsByClassName("close");
var i;
for (i = 0; i < close.length; i++) {
close[i].onclick = function() {
var div = this.parentElement;
div.style.display = "none";
}
}
// Add a "checked" symbol when clicking on a list item
var list = document.querySelector('ul');
list.addEventListener('click', function(ev) {
if (ev.target.tagName === 'LI') {
ev.target.classList.toggle('checked');
}
}, false);
// Create a new list item when clicking on the "Add" button
function newElement() {
var li = document.createElement("li");
var inputValue = document.getElementById("myInput").value;
var t = document.createTextNode(inputValue);
li.appendChild(t);
if (inputValue === '') {
alert("You must write something!");
} else {
document.getElementById("myUL").appendChild(li);
}
document.getElementById("myInput").value = "";
var span = document.createElement("SPAN");
var txt = document.createTextNode("\u00D7");
span.className = "close";
span.appendChild(txt);
li.appendChild(span);
for (i = 0; i < close.length; i++) {
close[i].onclick = function() {
var div = this.parentElement;
div.style.display = "none";
}
}
}HTML CSS, JavaScript 计算器
HTML代码
<div class="center">
<h1>HTML CSS, JavaScript 计算器</h1>
<a href="https://github.com/guuibayer/simple-calculator" target="_blank"><i class="fa fa-github"></i></a>
<form name="calculator">
<input type="button" id="clear" class="btn other" value="C">
<input type="text" id="display">
<br>
<input type="button" class="btn number" value="7" onclick="get(this.value);">
<input type="button" class="btn number" value="8" onclick="get(this.value);">
<input type="button" class="btn number" value="9" onclick="get(this.value);">
<input type="button" class="btn operator" value="+" onclick="get(this.value);">
<br>
<input type="button" class="btn number" value="4" onclick="get(this.value);">
<input type="button" class="btn number" value="5" onclick="get(this.value);">
<input type="button" class="btn number" value="6" onclick="get(this.value);">
<input type="button" class="btn operator" value="*" onclick="get(this.value);">
<br>
<input type="button" class="btn number" value="1" onclick="get(this.value);">
<input type="button" class="btn number" value="2" onclick="get(this.value);">
<input type="button" class="btn number" value="3" onclick="get(this.value);">
<input type="button" class="btn operator" value="-" onclick="get(this.value);">
<br>
<input type="button" class="btn number" value="0" onclick="get(this.value);">
<input type="button" class="btn operator" value="." onclick="get(this.value);">
<input type="button" class="btn operator" value="/" onclick="get(this.value);">
<input type="button" class="btn other" value="=" onclick="calculates();">
</form>
</div>JavaScript代码
/* limpa o display */
document.getElementById("clear").addEventListener("click", function() {
document.getElementById("display").value = "";
});
/* recebe os valores */
function get(value) {
document.getElementById("display").value += value;
}
/* calcula */
function calculates() {
var result = 0;
result = document.getElementById("display").value;
document.getElementById("display").value = "";
document.getElementById("display").value = eval(result);
};HTML、CSS、JavaScript 实现下拉菜单效果
HTML代码
<!doctype html>
<html>
<head>
<meta charset="UTF-8" />
<title>Arrowination</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.3.0/css/font-awesome.min.css" />
</head>
<body>
<div class="section">
<div class="title">
click here
</div>
<div class="body">
<h2>Just look at the arrow above</h2>
Lorem ipsum dolor sit amet, consectetuer adipiscing elit, sed diam nonummy nibh euismod tincidunt ut laoreet dolore magna aliquam erat volutpat.
<br/>
<br/>
<span>Crafted by: <a href="http://linkedin.com/in/mrReiha">Reiha Hosseini</a></span>
</div>
</div>
<div class="section">
<div class="title">
click here
</div>
<div class="body">
<h2>Just look at the arrow above</h2>
Lorem ipsum dolor sit amet, consectetuer adipiscing elit, sed diam nonummy nibh euismod tincidunt ut laoreet dolore magna aliquam erat volutpat.
<br/>
<br/>
<span>Crafted by: <a href="http://linkedin.com/in/mrReiha">Reiha Hosseini</a></span>
</div>
</div>
<div class="section">
<div class="title">
click here
</div>
<div class="body">
<h2>Just look at the arrow above</h2>
Lorem ipsum dolor sit amet, consectetuer adipiscing elit, sed diam nonummy nibh euismod tincidunt ut laoreet dolore magna aliquam erat volutpat.
<br/>
<br/>
<span>Crafted by: <a href="http://linkedin.com/in/mrReiha">Reiha Hosseini</a></span>
</div>
</div>
</body>
</html>JavaScript代码
/**
* ---------------------------------------------
* Javscript is just for make elements clickable
* Effects are on the css only
* ---------------------------------------------
* @since 2015/06/10
* @author Reiha Hosseini ( @mrReiha )
*/
;!( function( w, d ) {
'use strict';
var titles = d.querySelectorAll( '.title' ),
i = 0,
len = titles.length;
for ( ; i < len; i++ )
titles[ i ].onclick = function( e ) {
for ( var j = 0; j < len; j++ )
if ( this != titles[ j ] )
titles[ j ].parentNode.className = titles[ j ].parentNode.className.replace( / open/i, '' );
var cn = this.parentNode.className;
this.parentNode.className = ~cn.search( /open/i ) ? cn.replace( / open/i, '' ) : cn + ' open';
};
})( this, document );- JS/CSS 各种操作信息提示效果
HTML代码
<h2>提示信息</h2>
<p>点击 "x" 关闭提示框。</p>
<div class="alert">
<span class="closebtn">×</span>
<strong>危险!</strong> 危险操作提示。
</div>
<div class="alert success">
<span class="closebtn">×</span>
<strong>成功!</strong> 操作成功提示。
</div>
<div class="alert info">
<span class="closebtn">×</span>
<strong>提示!</strong> 提示信息修改等。
</div>
<div class="alert warning">
<span class="closebtn">×</span>
<strong>警告!</strong> 提示当前操作要注意。
</div>JavaScript代码
var close = document.getElementsByClassName("closebtn");
var i;
for (i = 0; i < close.length; i++) {
close[i].onclick = function(){
var div = this.parentElement;
div.style.opacity = "0";
setTimeout(function(){ div.style.display = "none"; }, 600);
}
}JS/CSS 在屏幕底部弹出消息(snackbar)
HTML代码
<h2>Snackbar / Toast</h2>
<p>在屏幕底部弹出消息,作用与使用方法都与Toast类似</p>
<p>点击按钮显示提示信息,3 秒后消失</p>
<button onclick="myFunction()">显示 Snackbar</button>
<div id="snackbar">一些文本..</div>JavaScript代码
<h2>Snackbar / Toast</h2>
<p>在屏幕底部弹出消息,作用与使用方法都与Toast类似</p>
<p>点击按钮显示提示信息,3 秒后消失</p>
<button onclick="myFunction()">显示 Snackbar</button>
<div id="snackbar">一些文本..</div>JS/CSS 登录表单
HTML代码
<h2>登录表单</h2>
<button onclick="document.getElementById('id01').style.display='block'" style="width:auto;">登录</button>
<div id="id01" class="modal">
<form class="modal-content animate" action="/action_page.php">
<div class="imgcontainer">
<span onclick="document.getElementById('id01').style.display='none'" class="close" title="Close Modal">×</span>
<img src="https://static.runoob.com/images/mix/img_avatar.png" alt="Avatar" class="avatar">
</div>
<div class="container">
<label><b>Username</b></label>
<input type="text" placeholder="Enter Username" name="uname" required>
<label><b>Password</b></label>
<input type="password" placeholder="Enter Password" name="psw" required>
<button type="submit">登陆</button>
<input type="checkbox" checked="checked"> 记住我
</div>
<div class="container" style="background-color:#f1f1f1">
<button type="button" onclick="document.getElementById('id01').style.display='none'" class="cancelbtn">Cancel</button>
<span class="psw">Forgot <a href="#">password?</a></span>
</div>
</form>
</div>JavaScript代码
// 获取模型
var modal = document.getElementById('id01');
// 鼠标点击模型外区域关闭登录框
window.onclick = function(event) {
if (event.target == modal) {
modal.style.display = "none";
}
}JS/CSS 注册表单
HTML代码
<h2>注册表单</h2>
<button onclick="document.getElementById('id01').style.display='block'" style="width:auto;">注册</button>
<div id="id01" class="modal">
<span onclick="document.getElementById('id01').style.display='none'" class="close" title="Close Modal">×</span>
<form class="modal-content animate" action="/action_page.php">
<div class="container">
<label><b>Email</b></label>
<input type="text" placeholder="Enter Email" name="email" required>
<label><b>Password</b></label>
<input type="password" placeholder="Enter Password" name="psw" required>
<label><b>Repeat Password</b></label>
<input type="password" placeholder="Repeat Password" name="psw-repeat" required>
<input type="checkbox" checked="checked"> Remember me
<p>By creating an account you agree to our <a href="#">Terms & Privacy</a>.</p>
<div class="clearfix">
<button type="button" onclick="document.getElementById('id01').style.display='none'" class="cancelbtn">Cancel</button>
<button type="submit" class="signupbtn">Sign Up</button>
</div>
</div>
</form>
</div>JavaScript代码
// 获取模型
var modal = document.getElementById('id01');
// 鼠标点击模型外区域关闭登录框
window.onclick = function(event) {
if (event.target == modal) {
modal.style.display = "none";
}
}JavaScript 计算器(倒计时)
HTML代码
<p id="demo"></p>JavaScript代码
// Set the date we're counting down to
var countDownDate = new Date("Jan 5, 2028 15:37:25").getTime();
// Update the count down every 1 second
var x = setInterval(function() {
// Get todays date and time
var now = new Date().getTime();
// Find the distance between now an the count down date
var distance = countDownDate - now;
// Time calculations for days, hours, minutes and seconds
var days = Math.floor(distance / (1000 * 60 * 60 * 24));
var hours = Math.floor((distance % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
var minutes = Math.floor((distance % (1000 * 60 * 60)) / (1000 * 60));
var seconds = Math.floor((distance % (1000 * 60)) / 1000);
// Output the result in an element with id="demo"
document.getElementById("demo").innerHTML = days + "d " + hours + "h "
+ minutes + "m " + seconds + "s ";
// If the count down is over, write some text
if (distance < 0) {
clearInterval(x);
document.getElementById("demo").innerHTML = "EXPIRED";
}
}, 1000);JS/CSS 菜单按钮切换(打开/关闭)
HTML代码
<p>点击菜单按钮变为 "X":</p>
<div class="container" onclick="myFunction(this)">
<div class="bar1"></div>
<div class="bar2"></div>
<div class="bar3"></div>
</div>JavaScript代码
function myFunction(x) {
x.classList.toggle("change");
}JS/CSS 手风琴动画效果
HTML代码
<h2>手风琴动画</h2>
<p>点击以下选项显示折叠内容</p>
<button class="accordion">选项 1</button>
<div class="panel">
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.</p>
</div>
<button class="accordion">选项 2</button>
<div class="panel">
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.</p>
</div>
<button class="accordion">选项 3</button>
<div class="panel">
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.</p>
</div>JavaScript代码
var acc = document.getElementsByClassName("accordion");
var i;
for (i = 0; i < acc.length; i++) {
acc[i].onclick = function() {
this.classList.toggle("active");
var panel = this.nextElementSibling;
if (panel.style.maxHeight){
panel.style.maxHeight = null;
} else {
panel.style.maxHeight = panel.scrollHeight + "px";
}
}
}JS/CSS 带图标手风琴动画效果
HTML代码
<h2>带图标手风琴</h2>
<p>该实例选项添加了 “+” 号图标与 “-” 号图标。</p>
<button class="accordion">选项 1</button>
<div class="panel">
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.</p>
</div>
<button class="accordion">选项 2</button>
<div class="panel">
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.</p>
</div>
<button class="accordion">选项 3</button>
<div class="panel">
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.</p>
</div>JavaScript代码
var acc = document.getElementsByClassName("accordion");
var i;
for (i = 0; i < acc.length; i++) {
acc[i].onclick = function() {
this.classList.toggle("active");
var panel = this.nextElementSibling;
if (panel.style.maxHeight){
panel.style.maxHeight = null;
} else {
panel.style.maxHeight = panel.scrollHeight + "px";
}
}
}JS/CSS 选项卡
HTML代码
<p>点击各个选项卡查看内容:</p>
<div class="tab">
<button class="tablinks" onclick="openCity(event, 'London')">London</button>
<button class="tablinks" onclick="openCity(event, 'Paris')">Paris</button>
<button class="tablinks" onclick="openCity(event, 'Tokyo')">Tokyo</button>
</div>
<div id="London" class="tabcontent">
<h3>London</h3>
<p>London is the capital city of England.</p>
</div>
<div id="Paris" class="tabcontent">
<h3>Paris</h3>
<p>Paris is the capital of France.</p>
</div>
<div id="Tokyo" class="tabcontent">
<h3>Tokyo</h3>
<p>Tokyo is the capital of Japan.</p>
</div>JavaScript代码
function openCity(evt, cityName) {
var i, tabcontent, tablinks;
tabcontent = document.getElementsByClassName("tabcontent");
for (i = 0; i < tabcontent.length; i++) {
tabcontent[i].style.display = "none";
}
tablinks = document.getElementsByClassName("tablinks");
for (i = 0; i < tablinks.length; i++) {
tablinks[i].className = tablinks[i].className.replace(" active", "");
}
document.getElementById(cityName).style.display = "block";
evt.currentTarget.className += " active";
}JS/CSS 选项卡 – 淡入效果
HTML代码
<h3>选项卡 - 淡入效果</h3>
<div class="tab">
<button class="tablinks" onclick="openCity(event, 'London')">London</button>
<button class="tablinks" onclick="openCity(event, 'Paris')">Paris</button>
<button class="tablinks" onclick="openCity(event, 'Tokyo')">Tokyo</button>
</div>
<div id="London" class="tabcontent">
<h3>London</h3>
<p>London is the capital city of England.</p>
</div>
<div id="Paris" class="tabcontent">
<h3>Paris</h3>
<p>Paris is the capital of France.</p>
</div>
<div id="Tokyo" class="tabcontent">
<h3>Tokyo</h3>
<p>Tokyo is the capital of Japan.</p>JavaScript代码
function openCity(evt, cityName) {
var i, tabcontent, tablinks;
tabcontent = document.getElementsByClassName("tabcontent");
for (i = 0; i < tabcontent.length; i++) {
tabcontent[i].style.display = "none";
}
tablinks = document.getElementsByClassName("tablinks");
for (i = 0; i < tablinks.length; i++) {
tablinks[i].className = tablinks[i].className.replace(" active", "");
}
document.getElementById(cityName).style.display = "block";
evt.currentTarget.className += " active";
}JS/CSS 选项卡 – 设置默认选项
HTML代码
<p>该实例设置了默认显示的选项卡,在页面载入时触发指定 id 的 click 事件。</p>
<div class="tab">
<button class="tablinks" onclick="openCity(event, 'London')" id="defaultOpen">London</button>
<button class="tablinks" onclick="openCity(event, 'Paris')">Paris</button>
<button class="tablinks" onclick="openCity(event, 'Tokyo')">Tokyo</button>
</div>
<div id="London" class="tabcontent">
<h3>London</h3>
<p>London is the capital city of England.</p>
</div>
<div id="Paris" class="tabcontent">
<h3>Paris</h3>
<p>Paris is the capital of France.</p>
</div>
<div id="Tokyo" class="tabcontent">
<h3>Tokyo</h3>
<p>Tokyo is the capital of Japan.</p>
</div>JavaScript代码
function openCity(evt, cityName) {
var i, tabcontent, tablinks;
tabcontent = document.getElementsByClassName("tabcontent");
for (i = 0; i < tabcontent.length; i++) {
tabcontent[i].style.display = "none";
}
tablinks = document.getElementsByClassName("tablinks");
for (i = 0; i < tablinks.length; i++) {
tablinks[i].className = tablinks[i].className.replace(" active", "");
}
document.getElementById(cityName).style.display = "block";
evt.currentTarget.className += " active";
}
// 触发 id="defaultOpen" click 事件
document.getElementById("defaultOpen").click();JS/CSS 选项卡 – 设置关闭按钮
HTML代码
<p>点击 x 按钮关闭选项卡内容。</p>
<div class="tab">
<button class="tablinks" onclick="openCity(event, 'London')" id="defaultOpen">London</button>
<button class="tablinks" onclick="openCity(event, 'Paris')">Paris</button>
<button class="tablinks" onclick="openCity(event, 'Tokyo')">Tokyo</button>
</div>
<div id="London" class="tabcontent">
<span onclick="this.parentElement.style.display='none'" class="topright">x</span>
<h3>London</h3>
<p>London is the capital city of England.</p>
</div>
<div id="Paris" class="tabcontent">
<span onclick="this.parentElement.style.display='none'" class="topright">x</span>
<h3>Paris</h3>
<p>Paris is the capital of France.</p>
</div>
<div id="Tokyo" class="tabcontent">
<span onclick="this.parentElement.style.display='none'" class="topright">x</span>
<h3>Tokyo</h3>
<p>Tokyo is the capital of Japan.</p>
</div>JavaScript代码
function openCity(evt, cityName) {
var i, tabcontent, tablinks;
tabcontent = document.getElementsByClassName("tabcontent");
for (i = 0; i < tabcontent.length; i++) {
tabcontent[i].style.display = "none";
}
tablinks = document.getElementsByClassName("tablinks");
for (i = 0; i < tablinks.length; i++) {
tablinks[i].className = tablinks[i].className.replace(" active", "");
}
document.getElementById(cityName).style.display = "block";
evt.currentTarget.className += " active";
}
// 触发 id="defaultOpen" click 事件
document.getElementById("defaultOpen").click();JS/CSS 选项卡 – 垂直方向
HTML代码
<p>点击各个选项切换内容:</p>
<div class="tab">
<button class="tablinks" onclick="openCity(event, 'London')" id="defaultOpen">London</button>
<button class="tablinks" onclick="openCity(event, 'Paris')">Paris</button>
<button class="tablinks" onclick="openCity(event, 'Tokyo')">Tokyo</button>
</div>
<div id="London" class="tabcontent">
<h3>London</h3>
<p>London is the capital city of England.</p>
</div>
<div id="Paris" class="tabcontent">
<h3>Paris</h3>
<p>Paris is the capital of France.</p>
</div>
<div id="Tokyo" class="tabcontent">
<h3>Tokyo</h3>
<p>Tokyo is the capital of Japan.</p>
</div>JavaScript代码
function openCity(evt, cityName) {
var i, tabcontent, tablinks;
tabcontent = document.getElementsByClassName("tabcontent");
for (i = 0; i < tabcontent.length; i++) {
tabcontent[i].style.display = "none";
}
tablinks = document.getElementsByClassName("tablinks");
for (i = 0; i < tablinks.length; i++) {
tablinks[i].className = tablinks[i].className.replace(" active", "");
}
document.getElementById(cityName).style.display = "block";
evt.currentTarget.className += " active";
}
// 触发 id="defaultOpen" click 事件
document.getElementById("defaultOpen").click();JS/CSS 选项卡 – 幻灯片效果
HTML代码
<p>点击各个选项切换内容:</p>
<div id="London" class="tabcontent">
<h3>London</h3>
<p>London is the capital city of England.</p>
</div>
<div id="Paris" class="tabcontent">
<h3>Paris</h3>
<p>Paris is the capital of France.</p>
</div>
<div id="Tokyo" class="tabcontent">
<h3>Tokyo</h3>
<p>Tokyo is the capital of Japan.</p>
</div>
<div id="Oslo" class="tabcontent">
<h3>Oslo</h3>
<p>Oslo is the capital of Norway.</p>
</div>
<button class="tablink" onclick="openCity('London', this, 'red')" id="defaultOpen">London</button>
<button class="tablink" onclick="openCity('Paris', this, 'green')">Paris</button>
<button class="tablink" onclick="openCity('Tokyo', this, 'blue')">Tokyo</button>
<button class="tablink" onclick="openCity('Oslo', this, 'orange')">Oslo</button>JavaScript代码
function openCity(cityName,elmnt,color) {
var i, tabcontent, tablinks;
tabcontent = document.getElementsByClassName("tabcontent");
for (i = 0; i < tabcontent.length; i++) {
tabcontent[i].style.display = "none";
}
tablinks = document.getElementsByClassName("tablink");
for (i = 0; i < tablinks.length; i++) {
tablinks[i].style.backgroundColor = "";
}
document.getElementById(cityName).style.display = "block";
elmnt.style.backgroundColor = color;
}
// 触发 id="defaultOpen" click 事件
document.getElementById("defaultOpen").click();JS/CSS 响应式顶部导航样式实例
HTML代码
<div class="topnav" id="myTopnav">
<a href="#home">主页</a>
<a href="#news">新闻</a>
<a href="#contact">联系方式</a>
<a href="#about">关于我们</a>
<a href="javascript:void(0);" style="font-size:15px;" class="icon" onclick="myFunction()">☰</a>
</div>
<div style="padding-left:16px">
<h2>响应式顶部导航实例</h2>
<p>重置浏览器查看实例。</p>
</div>JavaScript代码
function myFunction() {
var x = document.getElementById("myTopnav");
if (x.className === "topnav") {
x.className += " responsive";
} else {
x.className = "topnav";
}
}JS/CSS 侧边栏动画实例
HTML代码
<div id="mySidenav" class="sidenav">
<a href="javascript:void(0)" class="closebtn" onclick="closeNav()">×</a>
<a href="#">About</a>
<a href="#">Services</a>
<a href="#">Clients</a>
<a href="#">Contact</a>
</div>
<h2>侧边栏动画实例</h2>
<p>点击以下菜单图标打开侧边栏</p>
<span style="font-size:30px;cursor:pointer" onclick="openNav()">☰ 打开</span>JavaScript代码
function openNav() {
document.getElementById("mySidenav").style.width = "250px";
}
function closeNav() {
document.getElementById("mySidenav").style.width = "0";
}JS/CSS 侧边栏动画实例 - 页面主体内容向右移动
HTML代码
<div id="mySidenav" class="sidenav">
<a href="javascript:void(0)" class="closebtn" onclick="closeNav()">×</a>
<a href="#">About</a>
<a href="#">Services</a>
<a href="#">Clients</a>
<a href="#">Contact</a>
</div>
<div id="main">
<h2>侧边栏实例 - 页面主体向右移动</h2>
<p>点击以下菜单图标打开侧边栏,主体内容向右偏移。</p>
<span style="font-size:30px;cursor:pointer" onclick="openNav()">☰ 打开</span>
</div>JavaScript代码
function openNav() {
document.getElementById("mySidenav").style.width = "250px";
document.getElementById("main").style.marginLeft = "250px";
}
function closeNav() {
document.getElementById("mySidenav").style.width = "0";
document.getElementById("main").style.marginLeft= "0";
}JS/CSS 侧边栏动画实例 - 页面主体内容黑色透明背景
HTML代码
<div id="mySidenav" class="sidenav">
<a href="javascript:void(0)" class="closebtn" onclick="closeNav()">×</a>
<a href="#">About</a>
<a href="#">Services</a>
<a href="#">Clients</a>
<a href="#">Contact</a>
</div>
<div id="main">
<h2>侧边栏实例 - 页面主体向右移动</h2>
<p>点击以下菜单图标打开侧边栏,主体内容向右偏移。主体内容添加黑色透明背景</p>
<span style="font-size:30px;cursor:pointer" onclick="openNav()">☰ open</span>
</div>JavaScript代码
function openNav() {
document.getElementById("mySidenav").style.width = "250px";
document.getElementById("main").style.marginLeft = "250px";
document.body.style.backgroundColor = "rgba(0,0,0,0.4)";
}
function closeNav() {
document.getElementById("mySidenav").style.width = "0";
document.getElementById("main").style.marginLeft= "0";
document.body.style.backgroundColor = "white";
}JS/CSS 全屏幕侧边栏
HTML代码
<div id="mySidenav" class="sidenav">
<a href="javascript:void(0)" class="closebtn" onclick="closeNav()">×</a>
<a href="#">About</a>
<a href="#">Services</a>
<a href="#">Clients</a>
<a href="#">Contact</a>
</div>
<h2>全屏幕侧边栏</h2>
<p>点击以下菜单图标打开侧边栏</p>
<span style="font-size:30px;cursor:pointer" onclick="openNav()">☰ 打开</span>JavaScript代码
function openNav() {
document.getElementById("mySidenav").style.width = "100%";
}
function closeNav() {
document.getElementById("mySidenav").style.width = "0";
}JS/CSS 侧边栏 - 无动画效果
HTML代码
<div id="mySidenav" class="sidenav">
<a href="javascript:void(0)" class="closebtn" onclick="closeNav()">×</a>
<a href="#">About</a>
<a href="#">Services</a>
<a href="#">Clients</a>
<a href="#">Contact</a>
</div>
<h2>侧边栏</h2>
<p>点击以下菜单图标打开侧边栏。</p>
<span style="font-size:30px;cursor:pointer" onclick="openNav()">☰ 打开</span>JavaScript代码
function openNav() {
document.getElementById("mySidenav").style.display = "block";
}
function closeNav() {
document.getElementById("mySidenav").style.display = "none";
}JS/CSS 右侧侧边栏
HTML代码
<div id="mySidenav" class="sidenav">
<a href="javascript:void(0)" class="closebtn" onclick="closeNav()">×</a>
<a href="#">About</a>
<a href="#">Services</a>
<a href="#">Clients</a>
<a href="#">Contact</a>
</div>
<h2>右侧侧边栏</h2>
<p>点击以下菜单图标打开侧边栏,并显示在右侧。</p>
<span style="font-size:30px;cursor:pointer" onclick="openNav()">☰ 打开</span>JavaScript代码
function openNav() {
document.getElementById("mySidenav").style.width = "250px";
}
function closeNav() {
document.getElementById("mySidenav").style.width = "0";
}JS/CSS 全屏幕导航 – 从上到下动画
HTML代码
<div id="myNav" class="overlay">
<a href="javascript:void(0)" class="closebtn" onclick="closeNav()">×</a>
<div class="overlay-content">
<a href="#">About</a>
<a href="#">Services</a>
<a href="#">Clients</a>
<a href="#">Contact</a>
</div>
</div>
<h2>全屏幕导航 - 从上到下动画</h2>
<p>点击以下菜单图标打开导航菜单</p>
<span style="font-size:30px;cursor:pointer" onclick="openNav()">☰ 打开</span>JavaScript代码
function openNav() {
document.getElementById("myNav").style.height = "100%";
}
function closeNav() {
document.getElementById("myNav").style.height = "0%";
}JS/CSS 点击式下拉菜单
HTML代码
<h2>可点击的下拉菜单</h2>
<p>点击按钮显示下拉菜单</p>
<div class="dropdown">
<button onclick="myFunction()" class="dropbtn">下拉菜单</button>
<div id="myDropdown" class="dropdown-content">
<a href="#home">Home</a>
<a href="#about">About</a>
<a href="#contact">Contact</a>
</div>
</div>JavaScript代码
/* 点击按钮,下拉菜单在 显示/隐藏 之间切换 */
function myFunction() {
document.getElementById("myDropdown").classList.toggle("show");
}
// 点击下拉菜单意外区域隐藏
window.onclick = function(event) {
if (!event.target.matches('.dropbtn')) {
var dropdowns = document.getElementsByClassName("dropdown-content");
var i;
for (i = 0; i < dropdowns.length; i++) {
var openDropdown = dropdowns[i];
if (openDropdown.classList.contains('show')) {
openDropdown.classList.remove('show');
}
}
}
}JS/CSS 点击式下拉菜单 - 右对齐
HTML代码
<h2>可点击的下拉菜单 - 右对齐</h2>
<p>使用 <strong>float: right</strong> 让下拉菜单显示在右边。</p>
<div class="dropdown">
<button onclick="myFunction()" class="dropbtn">Dropdown</button>
<div id="myDropdown" class="dropdown-content">
<a href="#home">Home</a>
<a href="#about">About</a>
<a href="#contact">Contact</a>
</div>
</div>JavaScript代码
/* 点击按钮,下拉菜单在 显示/隐藏 之间切换 */
function myFunction() {
document.getElementById("myDropdown").classList.toggle("show");
}
// 点击下拉菜单意外区域隐藏
window.onclick = function(event) {
if (!event.target.matches('.dropbtn')) {
var dropdowns = document.getElementsByClassName("dropdown-content");
var i;
for (i = 0; i < dropdowns.length; i++) {
var openDropdown = dropdowns[i];
if (openDropdown.classList.contains('show')) {
openDropdown.classList.remove('show');
}
}
}
}JS/CSS 点击式导航栏下拉菜单
HTML代码
<div class="container">
<a href="#home">主页</a>
<a href="#news">新闻</a>
<div class="dropdown">
<button class="dropbtn" onclick="myFunction()">下拉菜单</button>
<div class="dropdown-content" id="myDropdown">
<a href="#">Link 1</a>
<a href="#">Link 2</a>
<a href="#">Link 3</a>
</div>
</div>
</div>
<h3>导航栏中的下拉菜单</h3>
<p>点击按钮显示下拉菜单</p>JavaScript代码
/* 点击按钮,下拉菜单在 显示/隐藏 之间切换 */
function myFunction() {
document.getElementById("myDropdown").classList.toggle("show");
}
// 点击下拉菜单意外区域隐藏
window.onclick = function(e) {
if (!e.target.matches('.dropbtn')) {
var myDropdown = document.getElementById("myDropdown");
if (myDropdown.classList.contains('show')) {
myDropdown.classList.remove('show');
}
}
}JS/CSS 下拉菜单可进行搜索/过滤操作
HTML代码
<h2>搜索/过滤</h2>
<p>点击按钮显示下拉菜单,输入框可以搜索过滤内容。</p>
<div class="dropdown">
<button onclick="myFunction()" class="dropbtn">下拉菜单</button>
<div id="myDropdown" class="dropdown-content">
<input type="text" placeholder="搜索.." id="myInput" onkeyup="filterFunction()">
<a href="#about">About</a>
<a href="#base">Base</a>
<a href="#blog">Blog</a>
<a href="#contact">Contact</a>
<a href="#custom">Custom</a>
<a href="#support">Support</a>
<a href="#tools">Tools</a>
</div>
</div>JavaScript代码
/* 点击按钮可以显示或隐藏下拉菜单 */
function myFunction() {
document.getElementById("myDropdown").classList.toggle("show");
}
function filterFunction() {
var input, filter, ul, li, a, i;
input = document.getElementById("myInput");
filter = input.value.toUpperCase();
div = document.getElementById("myDropdown");
a = div.getElementsByTagName("a");
for (i = 0; i < a.length; i++) {
if (a[i].innerHTML.toUpperCase().indexOf(filter) > -1) {
a[i].style.display = "";
} else {
a[i].style.display = "none";
}
}
}JS 联想、自动补齐功能
HTML代码
<!-- 关闭自带的自动补全功能 -->
<form autocomplete="off" action="/action_page.php">
<div class="autocomplete" style="width:300px;">
<input id="myInput" type="text" name="myCountry" placeholder="输入国家或地区英文名...">
</div>
<input type="submit">
</form>JavaScript代码
function autocomplete(inp, arr) {
/*函数主要有两个参数:文本框元素和自动补齐的完整数据*/
var currentFocus;
/* 监听 - 在写入时触发 */
inp.addEventListener("input", function(e) {
var a, b, i, val = this.value;
/*关闭已经打开的自动完成值列表*/
closeAllLists();
if (!val) { return false;}
currentFocus = -1;
/*创建列表*/
a = document.createElement("DIV");
a.setAttribute("id", this.id + "autocomplete-list");
a.setAttribute("class", "autocomplete-items");
/*添加 DIV 元素*/
this.parentNode.appendChild(a);
/*循环数组...*/
for (i = 0; i < arr.length; i++) {
/*检查选项是否以与文本字段值相同的字母开头*/
if (arr[i].substr(0, val.length).toUpperCase() == val.toUpperCase()) {
/*为匹配元素创建 DIV*/
b = document.createElement("DIV");
/*使匹配字母变粗体*/
b.innerHTML = "<strong>" + arr[i].substr(0, val.length) + "</strong>";
b.innerHTML += arr[i].substr(val.length);
/*insert a input field that will hold the current array item's value:*/
b.innerHTML += "<input type='hidden' value='" + arr[i] + "'>";
/*execute a function when someone clicks on the item value (DIV element):*/
b.addEventListener("click", function(e) {
/*insert the value for the autocomplete text field:*/
inp.value = this.getElementsByTagName("input")[0].value;
/*close the list of autocompleted values,
(or any other open lists of autocompleted values:*/
closeAllLists();
});
a.appendChild(b);
}
}
});
/*execute a function presses a key on the keyboard:*/
inp.addEventListener("keydown", function(e) {
var x = document.getElementById(this.id + "autocomplete-list");
if (x) x = x.getElementsByTagName("div");
if (e.keyCode == 40) {
/*If the arrow DOWN key is pressed,
increase the currentFocus variable:*/
currentFocus++;
/*and and make the current item more visible:*/
addActive(x);
} else if (e.keyCode == 38) { //up
/*If the arrow UP key is pressed,
decrease the currentFocus variable:*/
currentFocus--;
/*and and make the current item more visible:*/
addActive(x);
} else if (e.keyCode == 13) {
/*If the ENTER key is pressed, prevent the form from being submitted,*/
e.preventDefault();
if (currentFocus > -1) {
/*and simulate a click on the "active" item:*/
if (x) x[currentFocus].click();
}
}
});
function addActive(x) {
/*a function to classify an item as "active":*/
if (!x) return false;
/*start by removing the "active" class on all items:*/
removeActive(x);
if (currentFocus >= x.length) currentFocus = 0;
if (currentFocus < 0) currentFocus = (x.length - 1);
/*add class "autocomplete-active":*/
x[currentFocus].classList.add("autocomplete-active");
}
function removeActive(x) {
/*a function to remove the "active" class from all autocomplete items:*/
for (var i = 0; i < x.length; i++) {
x[i].classList.remove("autocomplete-active");
}
}
function closeAllLists(elmnt) {
/*close all autocomplete lists in the document,
except the one passed as an argument:*/
var x = document.getElementsByClassName("autocomplete-items");
for (var i = 0; i < x.length; i++) {
if (elmnt != x[i] && elmnt != inp) {
x[i].parentNode.removeChild(x[i]);
}
}
}
/*execute a function when someone clicks in the document:*/
document.addEventListener("click", function (e) {
closeAllLists(e.target);
});
}
/*数组 - 包含所有国家或地区名*/
var countries = ["Afghanistan","Albania","Algeria","Andorra","Angola","Anguilla","Antigua & Barbuda","Argentina","Armenia","Aruba","Australia","Austria","Azerbaijan","Bahamas","Bahrain","Bangladesh","Barbados","Belarus","Belgium","Belize","Benin","Bermuda","Bhutan","Bolivia","Bosnia & Herzegovina","Botswana","Brazil","British Virgin Islands","Brunei","Bulgaria","Burkina Faso","Burundi","Cambodia","Cameroon","Canada","Cape Verde","Cayman Islands","Central Arfrican Republic","Chad","Chile","China","Colombia","Congo","Cook Islands","Costa Rica","Cote D Ivoire","Croatia","Cuba","Curacao","Cyprus","Czech Republic","Denmark","Djibouti","Dominica","Dominican Republic","Ecuador","Egypt","El Salvador","Equatorial Guinea","Eritrea","Estonia","Ethiopia","Falkland Islands","Faroe Islands","Fiji","Finland","France","French Polynesia","French West Indies","Gabon","Gambia","Georgia","Germany","Ghana","Gibraltar","Greece","Greenland","Grenada","Guam","Guatemala","Guernsey","Guinea","Guinea Bissau","Guyana","Haiti","Honduras","Hong Kong China","Hungary","Iceland","India","Indonesia","Iran","Iraq","Ireland","Isle of Man","Israel","Italy","Jamaica","Japan","Jersey","Jordan","Kazakhstan","Kenya","Kiribati","Kosovo","Kuwait","Kyrgyzstan","Laos","Latvia","Lebanon","Lesotho","Liberia","Libya","Liechtenstein","Lithuania","Luxembourg","Macau China","Macedonia","Madagascar","Malawi","Malaysia","Maldives","Mali","Malta","Marshall Islands","Mauritania","Mauritius","Mexico","Micronesia","Moldova","Monaco","Mongolia","Montenegro","Montserrat","Morocco","Mozambique","Myanmar","Namibia","Nauro","Nepal","Netherlands","Netherlands Antilles","New Caledonia","New Zealand","Nicaragua","Niger","Nigeria","North Korea","Norway","Oman","Pakistan","Palau","Palestine","Panama","Papua New Guinea","Paraguay","Peru","Philippines","Poland","Portugal","Puerto Rico","Qatar","Reunion","Romania","Russia","Rwanda","Saint Pierre & Miquelon","Samoa","San Marino","Sao Tome and Principe","Saudi Arabia","Senegal","Serbia","Seychelles","Sierra Leone","Singapore","Slovakia","Slovenia","Solomon Islands","Somalia","South Africa","South Korea","South Sudan","Spain","Sri Lanka","St Kitts & Nevis","St Lucia","St Vincent","Sudan","Suriname","Swaziland","Sweden","Switzerland","Syria","Taiwan China","Tajikistan","Tanzania","Thailand","Timor L'Este","Togo","Tonga","Trinidad & Tobago","Tunisia","Turkey","Turkmenistan","Turks & Caicos","Tuvalu","Uganda","Ukraine","United Arab Emirates","United Kingdom","United States of America","Uruguay","Uzbekistan","Vanuatu","Vatican City","Venezuela","Vietnam","Virgin Islands (US)","Yemen","Zambia","Zimbabwe"];
/*传递参数*/
autocomplete(document.getElementById("myInput"), countries);JavaScript 按下回车(Enter)键触发按钮点击事件
HTML代码
<h3>按下 Enter 触发按钮点击事件</h3>
<p>选中输入框,然后按下"Enter" 就会触发按钮的点击事件。</p>
<input id="myInput" value="一些文本..">
<button id="myBtn" onclick="javascript:alert('Hello World!')">按钮</button>JavaScript代码
var input = document.getElementById("myInput");
input.addEventListener("keyup", function(event) {
event.preventDefault();
if (event.keyCode === 13) {
document.getElementById("myBtn").click();
}
});JavaScript 创建一个菜单搜索
HTML代码
<div class="row">
<div class="left" style="background-color:#bbb;">
<h2>菜单</h2>
<input type="text" id="mySearch" onkeyup="myFunction()" placeholder="搜索.." title="输入分类">
<ul id="myMenu">
<li><a href="#">HTML</a></li>
<li><a href="#">CSS</a></li>
<li><a href="#">JavaScript</a></li>
<li><a href="#">PHP</a></li>
<li><a href="#">Python</a></li>
<li><a href="#">jQuery</a></li>
<li><a href="#">SQL</a></li>
<li><a href="#">Bootstrap</a></li>
<li><a href="#">Node.js</a></li>
<li><a href="#">中文分类</a></li>
</ul>
</div>
<div class="right" style="background-color:#ddd;">
<h2>内容</h2>
<p>在搜索框输入菜单列表的分类名搜索对应内容。</p>
<p>Some text..Some text..Some text..Some text..Some text..Some text..Some text..Some text..</p>
<p>Some other text..Some text..Some text..Some text..Some text..Some text..Some text..Some text..</p>
<p>Some text..</p>
</div>
</div>JavaScript代码
function myFunction() {
var input, filter, ul, li, a, i;
input = document.getElementById("mySearch");
filter = input.value.toUpperCase();
ul = document.getElementById("myMenu");
li = ul.getElementsByTagName("li");
for (i = 0; i < li.length; i++) {
a = li[i].getElementsByTagName("a")[0];
if (a.innerHTML.toUpperCase().indexOf(filter) > -1) {
li[i].style.display = "";
} else {
li[i].style.display = "none";
}
}
}Javascript 判断是移动端浏览器还是 PC 端浏览器
HTML代码
<p>
JavaScript 判断当期设备是移动端浏览器还是 PC 端浏览器。
</p>
<hr>JavaScript代码
if( /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent) ) {
document.write("移动")
} else {
document.write("PC")
}JavaScript 判断是否微信浏览器
HTML代码
<p>
JavaScript 判断是否在微信浏览器中打开。
</p>
<hr>JavaScript代码
function is_weixn(){
var ua = navigator.userAgent.toLowerCase();
if(ua.match(/MicroMessenger/i)=="micromessenger") {
return true;
} else {
return false;
}
}
if( is_weixn() ) {
document.write("微信浏览器")
} else {
document.write("其他浏览器")
}
学员评价