js-js range collapsee-body android新增沉浸模式

任何时候都不要抱着疏忽的心理,不然,一不小心就被疏忽忽悠
Android与Js基本交互
一直都想写博客,但是一直因为工作、个人时间安排不合理等等各方面原因,一直没有成功(&_&)。不过很开心,今天终于可以付诸行动。分享,带给人乐趣的同时,自己也是种重新学习。
  记得去年做项目的时候,有一天快下班,突然下来一个任务,要求给项目添加一段Js的注入代码,附加一个新功能,当天就要完成。当时听到第一个反应:有点模糊。太久没用了,脑袋里只模糊记得一些用法,但具体细节已经记不清了。当时心里就在想,什么时候写一篇关于Android和Js交互的博客,这样以后要是再忘记了,可以随时翻看,也可以为正好用到的朋友提供一个参考。
Android和Js的交互,主要就是分两个部分,一部分:Android调用Js内部的方法;另一部分:Js调用Android端开放的接口方法。Android调用Js内部的方法,一般我们应该比较容易写出:
  Android端代码:
mWebview.loadUrl("javascript:jsMethod()");
  Js部分代码:
function jsMethod(){
document.getElementById("text").innerHTML = "我来自Android,调用Js内部的方法";
   当然,这是最简单的直接调用,我们也可以选择在Android端传入一些参数,然后在Js端进行相应的逻辑操作。比如,我们这里Js端有一个用来计算的内部方法:
function jsMethodToCount(a, b){
var r = a +
document.getElementById("text").innerHTML = "我来自Android,调用Js计算方法,计算结果为:" +
计算方法中,将外部传入的两个参数进行简单相加,然后在页面上显示计算结果。
  Android端相应调用:
mWebview.loadUrl("javascript:jsMethodToCount(121,8)")
   这样,Android调用Js的一个简单过程就完成了。Js调用Android,需要在Android端编写开放的接口方法,比如一个最简单的直接调用,
  Android端代码:
@JavascriptInterface
public void callAndroid(){
Log.w(TAG, "Js调Android callAndroid");
Toast.makeText(MainActivity.this, "Js调Android", Toast.LENGTH_SHORT).show();
  Js端代码:
function callAndroidMethodNoReturn(){
invokeTa.callAndroid();
  Js调Android接口,最简单的一种调用就完成了。我们当然也可以选择在Js端传入一些参数,然后Android端接收到参数,然后进行相应逻辑。
function callAndroidMethodNoReturn(a){
invokeTa.rideNoReturn(a);
  Android端接口方法代码:
@JavascriptInterface
public void rideNoReturn(int n){
Log.w(TAG, "Js调Android,接收到传入参数 n:" + n);
  运行一下,发现log输出,证明Js调Android接口方法成功,并且参数成功传入到Android端
05-02 18:37:19.457 13148-13182/com.example.androidandjs W/TAG MainActivity: Js调Android,接收到传入参数 n:100
  这是没有返回值的调用,如果Js端需要返回值,再进行二次的逻辑操作,那我们可以返回返回值,新建Android端接口方法:
@JavascriptInterface
public int ride(int n){
Log.w(TAG, "Js调Android,接收到传入参数 n:" + n);
int q = 300;
return q*n;
  Js端代码:
function callAndroidMethodWithReturn(a){
var result = invokeTa.ride(a);
document.getElementById("countText").innerHTML = "计算结果:"+
  运行程序,
  这里注意,Android端定义接口方法的时候,定义的接口方法名不能一样,不然不能识别,就算方法签名不同。比如,上面已经有个定义的接口方法ride(int n),如果我们再定义一个下面的接口方法
@JavascriptInterface
public int ride(int n, int b){
Log.w(TAG, "Js调Android,接收到传入参数(ride2) n:" + n);
return 300*n*b;
  然后点击Js触发新定义的接口方法,会发现没有效果,调用失效。Js识别不了相同方法名的函数,不管方法签名是否相同。
  到这里,Android和Js基本的相互调用,大致完成了。主要总结的一点:Android调用Js内部的方法,如果存在参数,参数是由Android端传入;Js调用Android端开放的接口方法,如果存在参数,参数是由Js端传入到Android端。参数来去理理清楚,当时公司要求新添加的需求,功能数据有些复杂,这些参数的来来去去,纠结了好一会(&_&)。
  完整代码:
public class MainActivity extends AppCompatActivity {
private static final String TAG = "TAG MainActivity";
private Button callJsMethodNoParams, callJsMethodWithP
private WebView mW
public void setupView(){
callJsMethodNoParams = (Button)findViewById(R.id.call_jsmethod_button);
callJsMethodWithParams = (Button)findViewById(R.id.call_jsmethod_withParams_button);
mWebview = (WebView)findViewById(R.id.webView);
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
setupView();
mWebview.getSettings().setJavaScriptEnabled(true);
mWebview.addJavascriptInterface(new MyJsObject(), "invokeTa");
mWebview.loadUrl("file:///android_asset/js.html");
addListener();
private void addListener() {
callJsMethodNoParams.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
mWebview.loadUrl("javascript:jsMethod('我来自Android,调用Js')");
callJsMethodWithParams.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
mWebview.loadUrl("javascript:jsMethodToCount(121,8)");
private class MyJsObject {
@JavascriptInterface
public void callAndroid(){
Log.w(TAG, "Js调Android callAndroid");
Toast.makeText(MainActivity.this, "Js调Android", Toast.LENGTH_SHORT).show();
@JavascriptInterface
public void rideNoReturn(int n){
Log.w(TAG, "Js调Android,接收到传入参数 n:" + n);
@JavascriptInterface
public int ride(int n){
Log.w(TAG, "Js调Android,接收到传入参数 n:" + n);
return 300*n;
  js.html代码:
type="text/javascript"&
&!--Js内部方法,供Android调用--&
function jsMethod(){
document.getElementById("text").innerHTML = "我来自Android,调用Js内部的方法";
function jsMethodToCount(a, b){
var r = a +
document.getElementById("text").innerHTML = "我来自Android,调用Js内部的计算方法,计算结果:" +
&!--Js调用Android中的无返回值方法 --&
function callAndroidMethodNoReturn(){
invokeTa.callAndroid();
function callAndroidMethodNoReturn(a){
invokeTa.rideNoReturn(a);
&!--Js调用Android中的有返回值方法 --&
function callAndroidMethodWithReturn(a){
var result = invokeTa.ride(a);
document.getElementById("countText").innerHTML = "计算结果:"+
id="text" cols="35" rows="2"&&/&
onclick="callAndroidMethodNoReturn(100)"&Js调用Android中的无返回值方法(有参)&/&
onclick="callAndroidMethodWithReturn(100)"&Js调用Android中的有返回值方法&/&
id="countText" cols="35" rows="2"&&/&
  注意的细节:在写的案例里,因为使用的是本地的js文件,所以不需要使用到网络权限,如果是要用到网络上的js文件,记得在AndroidManifest.xml里添加网络权限:
android:name="android.permission.INTERNET"/&
  然后Android调用Js的方法,是直接在代码里写死调用,也可以选择动态注入调用
String js = "var newscript = document.createElement(\"script\");";
js += "newscript.src=\"" + url + "\";";
js += String.format("newscript.onload=function(){%s;};", xxx());
js += "document.body.appendChild(newscript);";
mWebview.loadUrl("javascript:" + js);
  第一次写博客,有很多不足,也可能有很多表述不清晰或错误的地方,希望朋友们不吝指出。然后第一次弄,项目运行的gif效果,还不会弄,争取下一次的博客里添上。
没有更多推荐了,
加入CSDN,享受更精准的内容推荐,与500万程序员共同成长!如何动态兼容沉浸式状态栏模式_百度知道
如何动态兼容沉浸式状态栏模式
我有更好的答案
由于各系统版本的限制,沉浸式状态栏对系统有要求(Android4.4及以上、iOS7.0及以上),如果要兼容各系统版本,需要动态判断当前环境是否支持沉浸式状态栏以及系统状态栏的高度:使用5+API- 判断当前环境是否支持沉浸式状态栏plus.navigator.isImmersedStatusbar()如果当前支持沉浸式状态栏则返回true,否则返回false。- 获取当前系统状态栏高度plus.navigator.getStatusbarHeight()获取系统状态栏高度,Number类型。其单位是逻辑像素值,即css中可直接使用的像素值,可能存在小数点。实际用法参考HelloH5应用的“plus/doc.html”:
// 创建加载内容窗口
var topoffset='45px';
if(plus.navigator.isImmersedStatusbar()){// 兼容immersed状态栏模式
// 获取状态栏高度并根据业务需求处理,这里重新计算了子窗口的偏移位置
topoffset=(Math.round(plus.navigator.getStatusbarHeight())+45)+'px';
// 使用偏移位置创建子窗口
wc=plus.webview.create(null,'doccontent',{top:topoffset,bottom:'0px',bounce:'vertical',bounceBackground:'#FFFFFF'});通过userAgent判断5+API需要在plusready事件后才能调用,通常此事件在DOM加载渲染后才会触发,无法再渲染前根据不同的状态来设置css。为了解决此问题,在支持5+API运行环境的userAgent中特定字段Html5Plus/1.0后添加Immersed标识,如下:&Html5Plus/1.0 (Immersed/30)&其中Immersed/后的30表示状态栏的高度,单位为逻辑像素值。可以使用正则表达式进行获取:var immersed = 0;var ms=(/Html5Plus\/.+\s\(.*(Immersed\/(\d+\.?\d*).*)\)/gi).exec(navigator.userAgent);if(ms&&ms.length&=3){ // 当前环境为沉浸式状态栏模式
immersed=parseFloat(ms[2]);// 获取状态栏的高度}immersed值如果大于0则表示当前环境支持沉浸式状态栏。获取状态栏高度后,可以使用js动态修改DOM元素的css属性来设置样式,如设置界面头区域的顶部内边距为状态栏的高度(避免系统状态栏与界面头重叠),示例如下:var t=document.getElementById('header');t&&t.style.paddingTop=immersed+'px';具体项目中可根据界面设计,灵活使用immersed值来动态适配各种效果。完整用法可参考HelloH5应用中的“js/immersed.js”
使用5+API- 判断当前环境是否支持沉浸式状态栏plus.navigator.isImmersedStatusbar()如果当前支持沉浸式状态栏则返回true,否则返回false。- 获取当前系统状态栏高度plus.navigator.getStatusbarHeight()获取系统状态栏高度,Number类型。其单位是逻辑像素值,即css中可直接使用的像素值,可能存在小数点。实际用法参考HelloH5应用的“plus/doc.html”:
// 创建加载内容窗口
var topoffset='45px';
if(plus.navigator.isImmersedStatusbar()){// 兼容immersed状态栏模式
// 获取状态栏高度并根据业务需求处理,这里重新计算了子窗口的偏移位置
topoffset=(Math.round(plus.navigator.getStatusbarHeight())+45)+'px';
// 使用偏移位置创建子窗口
wc=plus.webview.create(null,'doccontent',{top:topoffset,bottom:'0px',bounce:'vertical',bounceBackground:'#FFFFFF'});通过userAgent判断5+API需要在plusready事件后才能调用,通常此事件在DOM加载渲染后才会触发,无法再渲染前根据不同的状态来设置css。为了解决此问题,在支持5+API运行环境的userAgent中特定字段Html5Plus/1.0后添加Immersed标识,如下:&Html5Plus/1.0 (Immersed/30)&其中Immersed/后的30表示状态栏的高度,单位为逻辑像素值。可以使用正则表达式进行获取:var immersed = 0;var ms=(/Html5Plus\/.+\s\(.*(Immersed\/(\d+\.?\d*).*)\)/gi).exec(navigator.userAgent);if(ms&&ms.length&=3){ // 当前环境为沉浸式状态栏模式
immersed=parseFloat(ms[2]);// 获取状态栏的高度}immersed值如果大于0则表示当前环境支持沉浸式状态栏。获取状态栏高度后,可以使用js动态修改DOM元素的css属性来设置样式,如设置界面头区域的顶部内边距为状态栏的高度(避免系统状态栏与界面头重叠),示例如下:var t=document.getElementById('header');t&&t.style.paddingTop=immersed+'px';具体项目中可根据界面设计,灵活使用immersed值来动态适配各种效果。完整用法可参考HelloH5应用中的“js/immersed.js”
为您推荐:
其他类似问题
换一换
回答问题,赢新手礼包
个人、企业类
违法有害信息,请在下方选择后提交
色情、暴力
我们会通过消息、邮箱等方式尽快将举报结果通知您。93#汽油, 积分 11841, 距离下一级还需 8159 积分
93#汽油, 积分 11841, 距离下一级还需 8159 积分
93#汽油, 积分 11841, 距离下一级还需 8159 积分
主题 : 176|帖子 : 2312|积分 : 11841
该用户从未签到
本帖最后由 用户名己占用 于
16:44 编辑
如何在安卓5.0上弄出沉浸式状态栏
相信有些小伙伴搞了XPOSED框架和Flat Style Colored Bars这样搞出来的的变色效果较差
状态栏不会跟随过渡动画变动只会单一的变色有时打开APP软件还没出来状态栏就先变色了
而今天我教大家的方法并非Flat Style Colored Bars
而是另一种插件我很难定义是沉浸式状态栏还是变色龙因为有变色龙的特性也有沉浸式状态栏的特性比如在过渡动画时你会感觉真的是沉浸的整体效果优于Flat Style Colored Bars在90%以上的场景中是符合Material Design设计语言的
你会很难发现那个是软件自带的沉浸的状态栏哪个是这个插件搞出来的状态栏具体有多牛逼我也说不清请大家自己体验
不说了,上图吧!
Screenshot_-19-40-29.png (768.22 KB, 下载次数: 200)
19:44 上传
Screenshot_-10-18-47.png (148.1 KB, 下载次数: 218)
10:39 上传
Screenshot_-10-21-47.png (101.85 KB, 下载次数: 232)
10:39 上传
自动排除已经沉浸的APP
Screenshot_-12-28-11.png (1.41 MB, 下载次数: 148)
13:31 上传
<font color="#月28日更新:Fixed the bug that some apps expand behind navigation bar
Remove black screens in several apps
Avoid freezing app
Tint navigation bar also
Match the app title color in&recent apps& with the status bar color
翻译:固定导航栏背后的错误,一些应用程序扩展在几个应用程序移除黑色屏幕避免冻结应用色导航栏也匹配应用程序标题颜色在最近的“应用程序”的状态栏的颜色
3月9日更新:Exclude fullscreen activities
Fix color for apps that automatically collapse ActionBar
Introduce Settings UI for customizations and blacklisting(and donation link via PayPal)
Decrease color refreshing interval
排除全屏活动
ActionBar修复颜色应用程序会自动崩溃
介绍设置UI定制和黑名单(通过贝宝和捐款链接)
减少颜色刷新间隔
个人已知BUG微信聊天拍照后不能直接发送
↓↓& && &&&教程回复可见哟& && &↓↓
首先,需要ROOT。安卓5.0中 设置-关于手机-版本号狂点击版本号
Screenshot_-00-21-30.png (178.66 KB, 下载次数: 78)
13:30 上传
即可打开开发者选项在开发者选项中可以打开ROOT权限
Screenshot_-00-21-41.png (157.56 KB, 下载次数: 79)
13:30 上传
接着需要XPOSED框架和我们的主角
(605.82 KB, 下载次数: 974)
13:34 上传
点击文件名下载附件
下载积分: 加油 -1
(3 MB, 下载次数: 1425)
13:35 上传
点击文件名下载附件
下载积分: 加油 -1
(30.7 KB, 下载次数: 1030)
16:44 上传
点击文件名下载附件
下载积分: 加油 -1
首先,先安装XPOSED框架apk(需要允许权限)然后安装Lolistat进入XPOSED里勾上Lolistat最后重启手机进入rec模式卡刷激活框架
完成后重启进入系统就完成了!
如果大家觉得每次OTA完后都要重新激活框架有些麻烦的话2楼有OTA完成后自动激活框架的教程!
<p id="rate_461" onmouseover="showTip(this)" tip="很给力!&加油 + 1
<p id="rate_320" onmouseover="showTip(this)" tip="很给力!&加油 + 1
<p id="rate_128" onmouseover="showTip(this)" tip="很给力!&加油 + 1
<p id="rate_361" onmouseover="showTip(this)" tip="很给力!&加油 + 1
<p id="rate_319" onmouseover="showTip(this)" tip="感谢分享&加油 + 50
93#汽油, 积分 11841, 距离下一级还需 8159 积分
93#汽油, 积分 11841, 距离下一级还需 8159 积分
93#汽油, 积分 11841, 距离下一级还需 8159 积分
主题 : 176|帖子 : 2312|积分 : 11841
该用户从未签到
本帖最后由 用户名己占用 于
14:09 编辑
CM12 OTA增量升级自动激活框架
1.将XPOSED框架卡刷激活包移动到内部储存-Cyandelte
MXC~2GU72]MBUNJR}7M$AQI.png (73.19 KB, 下载次数: 133)
14:06 上传
EU]W5}5Y0`9`HT1(EA)SJ{Q.png (46.69 KB, 下载次数: 125)
14:06 上传
2.进入CyanDelte点击屏幕右上角那个Settings那个符号
MAOT`9~[@%Z72OYD9OJ9BFQ.png (55.05 KB, 下载次数: 126)
14:06 上传
3.点击Install additional zip after ROM
YNBA3GK6~}W8Q@`}3@U@$RG.png (80.86 KB, 下载次数: 131)
14:06 上传
4.选择“激活框架.zip”
E$RK@JLC9MB@6@9L7F{HZH7.png (61.25 KB, 下载次数: 140)
14:06 上传
这就搞定了,以后每次OTA增量升级后都会卡刷这个包
煤油, 积分 2188, 距离下一级还需 2812 积分
煤油, 积分 2188, 距离下一级还需 2812 积分
煤油, 积分 2188, 距离下一级还需 2812 积分
主题 : 6|帖子 : 721|积分 : 2188
该用户从未签到
横杠啊。酷狗的沉浸是不带横杠的吧?
95#汽油, 积分 24919, 距离下一级还需 25081 积分
95#汽油, 积分 24919, 距离下一级还需 25081 积分
95#汽油, 积分 24919, 距离下一级还需 25081 积分
主题 : 42|帖子 : 2781|积分 : 24919
该用户从未签到
看看吧!!!!!!
---来自一加社区手机客户端
93#汽油, 积分 19433, 距离下一级还需 567 积分
93#汽油, 积分 19433, 距离下一级还需 567 积分
93#汽油, 积分 19433, 距离下一级还需 567 积分
主题 : 23|帖子 : 2851|积分 : 19433
该用户从未签到
卧槽,屌爆了的样子。。
柴油, 积分 9617, 距离下一级还需 383 积分
柴油, 积分 9617, 距离下一级还需 383 积分
柴油, 积分 9617, 距离下一级还需 383 积分
主题 : 21|帖子 : 2238|积分 : 9617
该用户从未签到
取色感觉不是很好
95#汽油, 积分 30774, 距离下一级还需 19226 积分
95#汽油, 积分 30774, 距离下一级还需 19226 积分
95#汽油, 积分 30774, 距离下一级还需 19226 积分
主题 : 366|帖子 : 8138|积分 : 30774
该用户从未签到
93#汽油, 积分 11841, 距离下一级还需 8159 积分
93#汽油, 积分 11841, 距离下一级还需 8159 积分
93#汽油, 积分 11841, 距离下一级还需 8159 积分
主题 : 176|帖子 : 2312|积分 : 11841
该用户从未签到
横杠啊。酷狗的沉浸是不带横杠的吧?
什么是横杆? 不太懂....
勾兑油, 积分 827, 距离下一级还需 173 积分
勾兑油, 积分 827, 距离下一级还需 173 积分
勾兑油, 积分 827, 距离下一级还需 173 积分
主题 : 13|帖子 : 202|积分 : 827
该用户从未签到
怎么做到的
煤油, 积分 3702, 距离下一级还需 1298 积分
煤油, 积分 3702, 距离下一级还需 1298 积分
煤油, 积分 3702, 距离下一级还需 1298 积分
主题 : 0|帖子 : 814|积分 : 3702
该用户从未签到
看看教程怎么搞
柴油, 积分 7932, 距离下一级还需 2068 积分
柴油, 积分 7932, 距离下一级还需 2068 积分
柴油, 积分 7932, 距离下一级还需 2068 积分
主题 : 30|帖子 : 1742|积分 : 7932
该用户从未签到
看看...........
柴油, 积分 8457, 距离下一级还需 1543 积分
柴油, 积分 8457, 距离下一级还需 1543 积分
柴油, 积分 8457, 距离下一级还需 1543 积分
主题 : 20|帖子 : 2231|积分 : 8457
该用户从未签到
?乛?乛?& & ?乛__乛?& & ?乛⌒乛?
柴油, 积分 7932, 距离下一级还需 2068 积分
柴油, 积分 7932, 距离下一级还需 2068 积分
柴油, 积分 7932, 距离下一级还需 2068 积分
主题 : 30|帖子 : 1742|积分 : 7932
该用户从未签到
还有一个沉浸,就是利用app settings 把应用设置成沉浸。(不需要经常看时间的应用)
主题 : 117|帖子 : 5531|积分 : 273547
该用户从未签到
不错不错,继续加油
润滑油, 积分 1311, 距离下一级还需 689 积分
润滑油, 积分 1311, 距离下一级还需 689 积分
润滑油, 积分 1311, 距离下一级还需 689 积分
主题 : 1|帖子 : 235|积分 : 1311
该用户从未签到
下载来试试
http://builds.cyngn.com/factory/bacon/cm-13.1-ZNH2KAS254-bacon-signed-9fbe6186fd.zip
柴油, 积分 6836, 距离下一级还需 3164 积分
柴油, 积分 6836, 距离下一级还需 3164 积分
柴油, 积分 6836, 距离下一级还需 3164 积分
主题 : 16|帖子 : 911|积分 : 6836
该用户从未签到
谢谢……………
润滑油, 积分 1683, 距离下一级还需 317 积分
润滑油, 积分 1683, 距离下一级还需 317 积分
润滑油, 积分 1683, 距离下一级还需 317 积分
主题 : 2|帖子 : 187|积分 : 1683
该用户从未签到
。。。。。。。。。。。。。。。。。。
掺水油, 积分 451, 距离下一级还需 49 积分
掺水油, 积分 451, 距离下一级还需 49 积分
掺水油, 积分 451, 距离下一级还需 49 积分
主题 : 11|帖子 : 350|积分 : 451
该用户从未签到
这是真的嘛
柴油, 积分 8308, 距离下一级还需 1692 积分
柴油, 积分 8308, 距离下一级还需 1692 积分
柴油, 积分 8308, 距离下一级还需 1692 积分
主题 : 6|帖子 : 1667|积分 : 8308
该用户从未签到
看看。。。。。
煤油, 积分 3788, 距离下一级还需 1212 积分
煤油, 积分 3788, 距离下一级还需 1212 积分
煤油, 积分 3788, 距离下一级还需 1212 积分
主题 : 0|帖子 : 381|积分 : 3788
该用户从未签到
这个得看看先
我是加油GG
祝加油GG男生节快乐
一周年 纪念勋章
一加一周年纪念勋章
在线小达人
社区上线100天纪念勋章
元旦纪念勋章
一加手机1勋章
马年纪念勋章 马上啥都有
圣诞节 勋章
圣诞节专属勋章
羊年纪念勋章
猴年纪念勋章 猴年猴赛雷
一加手机X勋章
二周年 纪念勋章
一加二周年纪念勋章
一加手机3勋章
三周年 纪念勋章
一加三周年纪念勋章
OnePlus 3T
一加手机3T勋章
鸡年纪念勋章
一加手机5勋章
庆祝 一加手机6板块开版
2018狗年勋章
植树节 勋章
植树节纪念勋章
一加手机2勋章
氢OS内测 荣誉勋章
一加社区氢OS内测加油纪念勋章
一加四周年纪念勋章
OnePlus 5T
一加手机5T勋章
狗年纪念勋章
元宵节 纪念勋章
祝加油们元宵节快乐!
我是零点控
零点控勋章 只为感谢而来
猴年特殊勋章
2014世界杯 纪念勋章
2014世界杯连续签到32天,给你一个证明自己是疯狂球迷的机会
一加社区感谢乐分享的你
一加社区玩机组专属勋章
加油头条 勋章
需通过限时活动申领
一加手机6勋章
深圳市万普拉斯科技有限公司 版权所有(<meta name="author" content="译者:王赛 ">
JavaScript 插件 & Bootstrap v3 中文文档
单个还是全部引入
JavaScript 插件可以单个引入(使用 Bootstrap 提供的单个 *.js 文件),或者一次性全部引入(使用 bootstrap.js 或压缩版的 bootstrap.min.js)。
建议使用压缩版的 JavaScript 文件
bootstrap.js 和 bootstrap.min.js 都包含了所有插件,你在使用时,只需选择一个引入页面就可以了。
插件之间的依赖关系
某些插件和 CSS 组件依赖于其它插件。如果你是单个引入每个插件的,请确保在文档中检查插件之间的依赖关系。注意,所有插件都依赖 jQuery (也就是说,jQuery必须在所有插件之前引入页面)。
文件中列出了 Bootstrap 所支持的 jQuery 版本。
你可以仅仅通过 data 属性 API 就能使用所有的 Bootstrap 插件,无需写一行 JavaScript 代码。这是 Bootstrap 中的一等 API,也应该是你的首选方式。
话又说回来,在某些情况下可能需要将此功能关闭。因此,我们还提供了关闭 data 属性 API 的方法,即解除以 data-api 为命名空间并绑定在文档上的事件。就像下面这样:
$(document).off('.data-api')
另外,如果是针对某个特定的插件,只需在 data-api 前面添加那个插件的名称作为命名空间,如下:
$(document).off('.alert.data-api')
Only one plugin per element via data attributes
Don't use data attributes from multiple plugins on the same element. For example, a button cannot both have a tooltip and toggle a modal. To accomplish this, use a wrapping element.
编程方式的 API
我们为所有 Bootstrap 插件提供了纯 JavaScript 方式的 API。所有公开的 API 都是支持单独或链式调用方式,并且返回其所操作的元素集合(注:和jQuery的调用形式一致)。
$('.btn.danger').button('toggle').addClass('fat')
所有方法都可以接受一个可选的 option 对象作为参数,或者一个代表特定方法的字符串,或者什么也不提供(在这种情况下,插件将会以默认值初始化):
$('#myModal').modal()
// 以默认值初始化
$('#myModal').modal({ keyboard: false })
// initialized with no keyboard
$('#myModal').modal('show')
// 初始化后立即调用 show 方法
每个插件还通过 Constructor 属性暴露了其原始的构造函数:$.fn.popover.Constructor。如果你想获取某个插件的实例,可以直接通过页面元素获取:$('[rel="popover"]').data('popover')。
每个插件都可以通过修改其自身的 Constructor.DEFAULTS 对象从而改变插件的默认设置:
$.fn.modal.Constructor.DEFAULTS.keyboard = false // 将模态框插件的 `keyboard` 默认选参数置为 false
避免命名空间冲突
某些时候可能需要将 Bootstrap 插件与其他 UI 框架共同使用。在这种情况下,命名空间冲突随时可能发生。如果不幸发生了这种情况,你可以通过调用插件的 .noConflict 方法恢复其原始值。
var bootstrapButton = $.fn.button.noConflict() // return $.fn.button to previously assigned value
$.fn.bootstrapBtn = bootstrapButton
// give $().bootstrapBtn the Bootstrap functionality
Bootstrap 为大部分插件所具有的动作提供了自定义事件。一般来说,这些事件都有不定式和过去式两种动词的命名形式,例如,不定式形式的动词(例如 show)表示其在事件开始时被触发;而过去式动词(例如 shown )表示在动作执行完毕之后被触发。
从 3.0.0 版本开始,所有 Bootstrap 事件的名称都采用命名空间方式。
所有以不定式形式的动词命名的事件都提供了 preventDefault 功能。这就赋予你在动作开始执行前将其停止的能力。
$('#myModal').on('show.bs.modal', function (e) {
if (!data) return e.preventDefault() // 阻止模态框的展示
每个 Bootstrap 的 jQuery 插件的版本号都可以通过插件的构造函数上的 VERSION 属性获取到。例如工具提示框(tooltip)插件:
$.fn.tooltip.Constructor.VERSION // =& "3.3.7"
未对禁用 JavaScript 的浏览器提供补救措施
Bootstrap 插件未对禁用 JavaScript 的浏览器提供补救措施。如果你对这种情况下的用户体验很关心的话,请添加
标签向你的用户进行解释(并告诉他们如何启用 JavaScript),或者按照你自己的方式提供补救措施。
第三方工具库
Bootstrap 官方不提供对第三方 JavaScript 工具库的支持,例如 Prototype 或 jQuery UI。除了 .noConflict 和为事件名称添加命名空间,还可能会有兼容性方面的问题,这就需要你自己来处理了。
关于过渡效果
对于简单的过渡效果,只需将 transition.js 和其它 JS 文件一起引入即可。如果你使用的是编译(或压缩)版的 bootstrap.js 文件,就无需再单独将其引入了。
包含的内容
Transition.js 是针对 transitionEnd 事件的一个基本辅助工具,也是对 CSS 过渡效果的模拟。它被其它插件用来检测当前浏览器对是否支持 CSS 的过渡效果。
禁用过度效果
通过下面的 JavaScript 代码可以在全局范围禁用过渡效果,并且必须将此代码放在 transition.js (或 bootstrap.js 或 bootstrap.min.js)后面,确保在 js 文件加载完毕后再执行下面的代码:
$.support.transition = false
模态框经过了优化,更加灵活,以弹出对话框的形式出现,具有最小和最实用的功能集。
不支持同时打开多个模态框
千万不要在一个模态框上重叠另一个模态框。要想同时支持多个模态框,需要自己写额外的代码来实现。
模态框的 HTML 代码放置的位置
务必将模态框的 HTML 代码放在文档的最高层级内(也就是说,尽量作为 body 标签的直接子元素),以避免其他组件影响模态框的展现和/或功能。
对于移动设备的附加说明
这里提供了在移动设备上使用模态框有一些附加说明。请参考章节。
Due to how HTML5 defines its semantics, the autofocus HTML attribute has no effect in Bootstrap modals. To achieve the same effect, use some custom JavaScript:
$('#myModal').on('shown.bs.modal', function () {
$('#myInput').focus()
以下模态框包含了模态框的头、体和一组放置于底部的按钮。
One fine body&
&div class="modal fade" tabindex="-1" role="dialog"&
&div class="modal-dialog" role="document"&
&div class="modal-content"&
&div class="modal-header"&
&button type="button" class="close" data-dismiss="modal" aria-label="Close"&&span aria-hidden="true"&&&/span&&/button&
&h4 class="modal-title"&Modal title&/h4&
&div class="modal-body"&
&p&One fine body&&/p&
&div class="modal-footer"&
&button type="button" class="btn btn-default" data-dismiss="modal"&Close&/button&
&button type="button" class="btn btn-primary"&Save changes&/button&
&/div&&!-- /.modal-content --&
&/div&&!-- /.modal-dialog --&
&/div&&!-- /.modal --&
点击下面的按钮即可通过 JavaScript 启动一个模态框。此模态框将从上到下、逐渐浮现到页面前。
Text in a modal
Duis mollis, est non commodo luctus, nisi erat porttitor ligula.
Popover in a modal
should trigger a popover on click.
Tooltips in a modal
should have tooltips on hover.
Overflowing text to show scroll behavior
Cras mattis consectetur purus sit amet fermentum. Cras justo odio, dapibus ac facilisis in, egestas eget quam. Morbi leo risus, porta ac consectetur ac, vestibulum at eros.
Praesent commodo cursus magna, vel scelerisque nisl consectetur et. Vivamus sagittis lacus vel augue laoreet rutrum faucibus dolor auctor.
Aenean lacinia bibendum nulla sed consectetur. Praesent commodo cursus magna, vel scelerisque nisl consectetur et. Donec sed odio dui. Donec ullamcorper nulla non metus auctor fringilla.
Cras mattis consectetur purus sit amet fermentum. Cras justo odio, dapibus ac facilisis in, egestas eget quam. Morbi leo risus, porta ac consectetur ac, vestibulum at eros.
Praesent commodo cursus magna, vel scelerisque nisl consectetur et. Vivamus sagittis lacus vel augue laoreet rutrum faucibus dolor auctor.
Aenean lacinia bibendum nulla sed consectetur. Praesent commodo cursus magna, vel scelerisque nisl consectetur et. Donec sed odio dui. Donec ullamcorper nulla non metus auctor fringilla.
Cras mattis consectetur purus sit amet fermentum. Cras justo odio, dapibus ac facilisis in, egestas eget quam. Morbi leo risus, porta ac consectetur ac, vestibulum at eros.
Praesent commodo cursus magna, vel scelerisque nisl consectetur et. Vivamus sagittis lacus vel augue laoreet rutrum faucibus dolor auctor.
Aenean lacinia bibendum nulla sed consectetur. Praesent commodo cursus magna, vel scelerisque nisl consectetur et. Donec sed odio dui. Donec ullamcorper nulla non metus auctor fringilla.
Launch demo modal
&!-- Button trigger modal --&
&button type="button" class="btn btn-primary btn-lg" data-toggle="modal" data-target="#myModal"&
Launch demo modal
&!-- Modal --&
&div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel"&
&div class="modal-dialog" role="document"&
&div class="modal-content"&
&div class="modal-header"&
&button type="button" class="close" data-dismiss="modal" aria-label="Close"&&span aria-hidden="true"&&&/span&&/button&
&h4 class="modal-title" id="myModalLabel"&Modal title&/h4&
&div class="modal-body"&
&div class="modal-footer"&
&button type="button" class="btn btn-default" data-dismiss="modal"&Close&/button&
&button type="button" class="btn btn-primary"&Save changes&/button&
增强模态框的可访问性
务必为 .modal 添加 role="dialog" 和 aria-labelledby="..." 属性,用于指向模态框的标题栏;为 .modal-dialog 添加 aria-hidden="true" 属性。
另外,你还应该通过 aria-describedby 属性为模态框 .modal 添加描述性信息。
模态框提供了两个可选尺寸,通过为 .modal-dialog 增加一个样式调整类实现。
&!-- Large modal --&
&button type="button" class="btn btn-primary" data-toggle="modal" data-target=".bs-example-modal-lg"&Large modal&/button&
&div class="modal fade bs-example-modal-lg" tabindex="-1" role="dialog" aria-labelledby="myLargeModalLabel"&
&div class="modal-dialog modal-lg" role="document"&
&div class="modal-content"&
&!-- Small modal --&
&button type="button" class="btn btn-primary" data-toggle="modal" data-target=".bs-example-modal-sm"&Small modal&/button&
&div class="modal fade bs-example-modal-sm" tabindex="-1" role="dialog" aria-labelledby="mySmallModalLabel"&
&div class="modal-dialog modal-sm" role="document"&
&div class="modal-content"&
禁止动画效果
如果你不需要模态框弹出时的动画效果(淡入淡出效果),删掉 .fade 类即可。
&div class="modal" tabindex="-1" role="dialog" aria-labelledby="..."&
Using the grid system
To take advantage of the Bootstrap grid system within a modal, just nest .rows within the .modal-body and then use the normal grid system classes.
.col-md-4 .col-md-offset-4
.col-md-3 .col-md-offset-3
.col-md-2 .col-md-offset-4
.col-md-6 .col-md-offset-3
Level 1: .col-sm-9
Level 2: .col-xs-8 .col-sm-6
Level 2: .col-xs-4 .col-sm-6
Launch demo modal
&div class="modal fade" tabindex="-1" role="dialog" aria-labelledby="gridSystemModalLabel"&
&div class="modal-dialog" role="document"&
&div class="modal-content"&
&div class="modal-header"&
&button type="button" class="close" data-dismiss="modal" aria-label="Close"&&span aria-hidden="true"&&&/span&&/button&
&h4 class="modal-title" id="gridSystemModalLabel"&Modal title&/h4&
&div class="modal-body"&
&div class="row"&
&div class="col-md-4"&.col-md-4&/div&
&div class="col-md-4 col-md-offset-4"&.col-md-4 .col-md-offset-4&/div&
&div class="row"&
&div class="col-md-3 col-md-offset-3"&.col-md-3 .col-md-offset-3&/div&
&div class="col-md-2 col-md-offset-4"&.col-md-2 .col-md-offset-4&/div&
&div class="row"&
&div class="col-md-6 col-md-offset-3"&.col-md-6 .col-md-offset-3&/div&
&div class="row"&
&div class="col-sm-9"&
Level 1: .col-sm-9
&div class="row"&
&div class="col-xs-8 col-sm-6"&
Level 2: .col-xs-8 .col-sm-6
&div class="col-xs-4 col-sm-6"&
Level 2: .col-xs-4 .col-sm-6
&div class="modal-footer"&
&button type="button" class="btn btn-default" data-dismiss="modal"&Close&/button&
&button type="button" class="btn btn-primary"&Save changes&/button&
&/div&&!-- /.modal-content --&
&/div&&!-- /.modal-dialog --&
&/div&&!-- /.modal --&
Varying modal content based on trigger button
Have a bunch of buttons that all trigger the same modal, just with slightly different contents? Use event.relatedTarget and
(possibly ) to vary the contents of the modal depending on which button was clicked. See the Modal Events docs for details on relatedTarget,
Open modal for @mdo
Open modal for @fat
Open modal for @getbootstrap
...more buttons...
Recipient:
&button type="button" class="btn btn-primary" data-toggle="modal" data-target="#exampleModal" data-whatever="@mdo"&Open modal for @mdo&/button&
&button type="button" class="btn btn-primary" data-toggle="modal" data-target="#exampleModal" data-whatever="@fat"&Open modal for @fat&/button&
&button type="button" class="btn btn-primary" data-toggle="modal" data-target="#exampleModal" data-whatever="@getbootstrap"&Open modal for @getbootstrap&/button&
...more buttons...
&div class="modal fade" id="exampleModal" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel"&
&div class="modal-dialog" role="document"&
&div class="modal-content"&
&div class="modal-header"&
&button type="button" class="close" data-dismiss="modal" aria-label="Close"&&span aria-hidden="true"&&&/span&&/button&
&h4 class="modal-title" id="exampleModalLabel"&New message&/h4&
&div class="modal-body"&
&div class="form-group"&
&label for="recipient-name" class="control-label"&Recipient:&/label&
&input type="text" class="form-control" id="recipient-name"&
&div class="form-group"&
&label for="message-text" class="control-label"&Message:&/label&
&textarea class="form-control" id="message-text"&&/textarea&
&div class="modal-footer"&
&button type="button" class="btn btn-default" data-dismiss="modal"&Close&/button&
&button type="button" class="btn btn-primary"&Send message&/button&
$('#exampleModal').on('show.bs.modal', function (event) {
var button = $(event.relatedTarget) // Button that triggered the modal
var recipient = button.data('whatever') // Extract info from data-* attributes
// If necessary, you could initiate an AJAX request here (and then do the updating in a callback).
// Update the modal's content. We'll use jQuery here, but you could use a data binding library or other methods instead.
var modal = $(this)
modal.find('.modal-title').text('New message to ' + recipient)
modal.find('.modal-body input').val(recipient)
通过 data 属性或 JavaScript 调用模态框插件,可以根据需要动态展示隐藏的内容。模态框弹出时还会为 &body& 元素添加 .modal-open 类,从而覆盖页面默认的滚动行为,并且还会自动生成一个 .modal-backdrop 元素用于提供一个可点击的区域,点击此区域就即可关闭模态框。
通过 data 属性
不需写 JavaScript 代码也可激活模态框。通过在一个起控制器作用的元素(例如:按钮)上添加 data-toggle="modal" 属性,或者 data-target="#foo" 属性,再或者 href="#foo" 属性,用于指向被控制的模态框。
&button type="button" data-toggle="modal" data-target="#myModal"&Launch modal&/button&
通过 JavaScript 调用
只需一行 JavaScript 代码,即可通过元素的 id myModal 调用模态框:
$('#myModal').modal(options)
可以将选项通过 data 属性或 JavaScript 代码传递。对于 data 属性,需要将参数名称放到 data- 之后,例如 data-backdrop=""。
boolean 或 字符串 'static'
Includes a modal-backdrop element. Alternatively, specify static for a backdrop which doesn't close the modal on click.
键盘上的 esc 键被按下时关闭模态框。
模态框初始化之后就立即显示出来。
This option is deprecated since v3.3.0 and has been removed in v4. We recommend instead using client-side templating or a data binding framework, or calling
如果提供的是 URL,将利用 jQuery 的 load 方法从此 URL 地址加载要展示的内容(只加载一次)并插入 .modal-content 内。如果使用的是 data 属性 API,还可以利用 href 属性指定内容来源地址。下面是一个实例:
&a data-toggle="modal" href="remote.html" data-target="#modal"&Click me&/a&
.modal(options)
将页面中的某块内容作为模态框激活。接受可选参数 object。
$('#myModal').modal({
keyboard: false
.modal('toggle')
手动打开或关闭模态框。在模态框显示或隐藏之前返回到主调函数中(也就是,在触发 shown.bs.modal 或 hidden.bs.modal 事件之前)。
$('#myModal').modal('toggle')
.modal('show')
手动打开模态框。在模态框显示之前返回到主调函数中 (也就是,在触发 shown.bs.modal 事件之前)。
$('#myModal').modal('show')
.modal('hide')
手动隐藏模态框。在模态框隐藏之前返回到主调函数中 (也就是,在触发 hidden.bs.modal 事件之前)。
$('#myModal').modal('hide')
.modal('handleUpdate')
Readjusts the modal's positioning to counter a scrollbar in case one should appear, which would make the modal jump to the left.
Only needed when the height of the modal changes while it is open.
$('#myModal').modal('handleUpdate')
Bootstrap 的模态框类提供了一些事件用于监听并执行你自己的代码。
All modal events are fired at the modal itself (i.e. at the &div class="modal"&).
show.bs.modal
show 方法调用之后立即触发该事件。如果是通过点击某个作为触发器的元素,则此元素可以通过事件的 relatedTarget 属性进行访问。
shown.bs.modal
此事件在模态框已经显示出来(并且同时在 CSS 过渡效果完成)之后被触发。如果是通过点击某个作为触发器的元素,则此元素可以通过事件的 relatedTarget 属性进行访问。
hide.bs.modal
hide 方法调用之后立即触发该事件。
hidden.bs.modal
此事件在模态框被隐藏(并且同时在 CSS 过渡效果完成)之后被触发。
loaded.bs.modal
从远端的数据源加载完数据之后触发该事件。
$('#myModal').on('hidden.bs.modal', function (e) {
// do something...
Add dropdown menus to nearly anything with this simple plugin, including the navbar, tabs, and pills.
Within a navbar
Within pills
Via data attributes or JavaScript, the dropdown plugin toggles hidden content (dropdown menus) by toggling the .open class on the parent list item.
On mobile devices, opening a dropdown adds a .dropdown-backdrop as a tap area for closing dropdown menus when tapping outside the menu, a requirement for proper iOS support. This means that switching from an open dropdown menu to a different dropdown menu requires an extra tap on mobile.
Note: The data-toggle="dropdown" attribute is relied on for closing dropdown menus at an application level, so it's a good idea to always use it.
Via data attributes
Add data-toggle="dropdown" to a link or button to toggle a dropdown.
&div class="dropdown"&
&button id="dLabel" type="button" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false"&
Dropdown trigger
&span class="caret"&&/span&
&ul class="dropdown-menu" aria-labelledby="dLabel"&
To keep URLs intact with link buttons, use the data-target attribute instead of href="#".
&div class="dropdown"&
&a id="dLabel" data-target="#" href="http://example.com" data-toggle="dropdown" role="button" aria-haspopup="true" aria-expanded="false"&
Dropdown trigger
&span class="caret"&&/span&
&ul class="dropdown-menu" aria-labelledby="dLabel"&
Via JavaScript
Call the dropdowns via JavaScript:
$('.dropdown-toggle').dropdown()
$().dropdown('toggle')
Toggles the dropdown menu of a given navbar or tabbed navigation.
All dropdown events are fired at the .dropdown-menu's parent element.
All dropdown events have a relatedTarget property, whose value is the toggling anchor element.
Event Type
Description
show.bs.dropdown
This event fires immediately when the show instance method is called.
shown.bs.dropdown
This event is fired when the dropdown has been made visible to the user (will wait for CSS transitions, to complete).
hide.bs.dropdown
This event is fired immediately when the hide instance method has been called.
hidden.bs.dropdown
This event is fired when the dropdown has finished being hidden from the user (will wait for CSS transitions, to complete).
$('#myDropdown').on('show.bs.dropdown', function () {
// do something…
导航条实例
滚动监听插件是用来根据滚动条所处的位置来自动更新导航项的。如下所示,滚动导航条下面的区域并关注导航项的变化。下拉菜单中的条目也会自动高亮显示。
Ad leggings keytar, brunch id art party dolor labore. Pitchfork yr enim lo-fi before they sold out qui. Tumblr farm-to-table bicycle rights whatever. Anim keffiyeh carles cardigan. Velit seitan mcsweeney's photo booth 3 wolf moon irure. Cosby sweater lomo jean shorts, williamsburg hoodie minim qui you probably haven't heard of them et cardigan trust fund culpa biodiesel wes anderson aesthetic. Nihil tattooed accusamus, cred irony biodiesel keffiyeh artisan ullamco consequat.
Veniam marfa mustache skateboard, adipisicing fugiat velit pitchfork beard. Freegan beard aliqua cupidatat mcsweeney's vero. Cupidatat four loko nisi, ea helvetica nulla carles. Tattooed cosby sweater food truck, mcsweeney's quis non freegan vinyl. Lo-fi wes anderson +1 sartorial. Carles non aesthetic exercitation quis gentrify. Brooklyn adipisicing craft beer vice keytar deserunt.
Occaecat commodo aliqua delectus. Fap craft beer deserunt skateboard ea. Lomo bicycle rights adipisicing banh mi, velit ea sunt next level locavore single-origin coffee in magna veniam. High life id vinyl, echo park consequat quis aliquip banh mi pitchfork. Vero VHS est adipisicing. Consectetur nisi DIY minim messenger bag. Cred ex in, sustainable delectus consectetur fanny pack iphone.
In incididunt echo park, officia deserunt mcsweeney's proident master cleanse thundercats sapiente veniam. Excepteur VHS elit, proident shoreditch +1 biodiesel laborum craft beer. Single-origin coffee wayfarers irure four loko, cupidatat terry richardson master cleanse. Assumenda you probably haven't heard of them art party fanny pack, tattooed nulla cardigan tempor ad. Proident wolf nesciunt sartorial keffiyeh eu banh mi sustainable. Elit wolf voluptate, lo-fi ea portland before they sold out four loko. Locavore enim nostrud mlkshk brooklyn nesciunt.
Ad leggings keytar, brunch id art party dolor labore. Pitchfork yr enim lo-fi before they sold out qui. Tumblr farm-to-table bicycle rights whatever. Anim keffiyeh carles cardigan. Velit seitan mcsweeney's photo booth 3 wolf moon irure. Cosby sweater lomo jean shorts, williamsburg hoodie minim qui you probably haven't heard of them et cardigan trust fund culpa biodiesel wes anderson aesthetic. Nihil tattooed accusamus, cred irony biodiesel keffiyeh artisan ullamco consequat.
Keytar twee blog, culpa messenger bag marfa whatever delectus food truck. Sapiente synth id assumenda. Locavore sed helvetica cliche irony, thundercats you probably haven't heard of them consequat hoodie gluten-free lo-fi fap aliquip. Labore elit placeat before they sold out, terry richardson proident brunch nesciunt quis cosby sweater pariatur keffiyeh ut helvetica artisan. Cardigan craft beer seitan readymade velit. VHS chambray laboris tempor veniam. Anim mollit minim commodo ullamco thundercats.
Resolvable ID targets required
Navbar links must have resolvable id targets. For example, a &a href="#home"&home&/a& must correspond to something in the DOM like &div id="home"&&/div&.
需要相对定位(relative positioning)
无论何种实现方式,滚动监听都需要被监听的组件是 position: 即相对定位方式。大多数时候是监听 &body& 元素。When scrollspying on elements other than the &body&, be sure to have a height set and overflow-y: applied.
通过 data 属性调用
To easily add scrollspy behavior to your topbar navigation, add data-spy="scroll" to the element you want to spy on (most typically this would be the &body&). Then add the data-target attribute with the ID or class of the parent element of any Bootstrap .nav component.
position: relative;
&body data-spy="scroll" data-target="#navbar-example"&
&div id="navbar-example"&
&ul class="nav nav-tabs" role="tablist"&
通过 JavaScript 调用
在 CSS 中添加 position: 之后,通过 JavaScript 代码启动滚动监听插件:
$('body').scrollspy({ target: '#navbar-example' })
.scrollspy('refresh')
当使用滚动监听插件的同时在 DOM 中添加或删除元素后,你需要像下面这样调用此刷新( refresh) 方法:
$('[data-spy="scroll"]').each(function () {
var $spy = $(this).scrollspy('refresh')
可以通过 data 属性或 JavaScript 传递参数。对于 data 属性,其名称是将参数名附着到 data- 后面组成,例如 data-offset=""。
计算滚动位置时相对于顶部的偏移量(像素数)。
activate.bs.scrollspy
每当一个新条目被激活后都将由滚动监听插件触发此事件。
$('#myScrollspy').on('activate.bs.scrollspy', function () {
// do something…
Example tabs
Add quick, dynamic tab functionality to transition through panes of local content, even via dropdown menus. Nested tabs are not supported.
Raw denim you probably haven't heard of them jean shorts Austin. Nesciunt tofu stumptown aliqua, retro synth master cleanse. Mustache cliche tempor, williamsburg carles vegan helvetica. Reprehenderit butcher retro keffiyeh dreamcatcher synth. Cosby sweater eu banh mi, qui irure terry richardson ex squid. Aliquip placeat salvia cillum iphone. Seitan aliquip quis cardigan american apparel, butcher voluptate nisi qui.
Food truck fixie locavore, accusamus mcsweeney's marfa nulla single-origin coffee squid. Exercitation +1 labore velit, blog sartorial PBR leggings next level wes anderson artisan four loko farm-to-table craft beer twee. Qui photo booth letterpress, commodo enim craft beer mlkshk aliquip jean shorts ullamco ad vinyl cillum PBR. Homo nostrud organic, assumenda labore aesthetic magna delectus mollit. Keytar helvetica VHS salvia yr, vero magna velit sapiente labore stumptown. Vegan fanny pack odio cillum wes anderson 8-bit, sustainable jean shorts beard ut DIY ethical culpa terry richardson biodiesel. Art party scenester stumptown, tumblr butcher vero sint qui sapiente accusamus tattooed echo park.
Etsy mixtape wayfarers, ethical wes anderson tofu before they sold out mcsweeney's organic lomo retro fanny pack lo-fi farm-to-table readymade. Messenger bag gentrify pitchfork tattooed craft beer, iphone skateboard locavore carles etsy salvia banksy hoodie helvetica. DIY synth PBR banksy irony. Leggings gentrify squid 8-bit cred pitchfork. Williamsburg banh mi whatever gluten-free, carles pitchfork biodiesel fixie etsy retro mlkshk vice blog. Scenester cred you probably haven't heard of them, vinyl craft beer blog stumptown. Pitchfork sustainable tofu synth chambray yr.
Trust fund seitan letterpress, keytar raw denim keffiyeh etsy art party before they sold out master cleanse gluten-free squid scenester freegan cosby sweater. Fanny pack portland seitan DIY, art party locavore wolf cliche high life echo park Austin. Cred vinyl keffiyeh DIY salvia PBR, banh mi before they sold out farm-to-table VHS viral locavore cosby sweater. Lomo wolf viral, mustache readymade thundercats keffiyeh craft beer marfa ethical. Wolf salvia freegan, sartorial keffiyeh echo park vegan.
Enable tabbable tabs via JavaScript (each tab needs to be activated individually):
$('#myTabs a').click(function (e) {
e.preventDefault()
$(this).tab('show')
You can activate individual tabs in several ways:
$('#myTabs a[href="#profile"]').tab('show') // Select tab by name
$('#myTabs a:first').tab('show') // Select first tab
$('#myTabs a:last').tab('show') // Select last tab
$('#myTabs li:eq(2) a').tab('show') // Select third tab (0-indexed)
You can activate a tab or pill navigation without writing any JavaScript by simply specifying data-toggle="tab" or data-toggle="pill" on an element. Adding the nav and nav-tabs classes to the tab ul will apply the Bootstrap , while adding the nav and nav-pills classes will apply .
&!-- Nav tabs --&
&ul class="nav nav-tabs" role="tablist"&
&li role="presentation" class="active"&&a href="#home" aria-controls="home" role="tab" data-toggle="tab"&Home&/a&&/li&
&li role="presentation"&&a href="#profile" aria-controls="profile" role="tab" data-toggle="tab"&Profile&/a&&/li&
&li role="presentation"&&a href="#messages" aria-controls="messages" role="tab" data-toggle="tab"&Messages&/a&&/li&
&li role="presentation"&&a href="#settings" aria-controls="settings" role="tab" data-toggle="tab"&Settings&/a&&/li&
&!-- Tab panes --&
&div class="tab-content"&
&div role="tabpanel" class="tab-pane active" id="home"&...&/div&
&div role="tabpanel" class="tab-pane" id="profile"&...&/div&
&div role="tabpanel" class="tab-pane" id="messages"&...&/div&
&div role="tabpanel" class="tab-pane" id="settings"&...&/div&
Fade effect
To make tabs fade in, add .fade to each .tab-pane. The first tab pane must also have .in to make the initial content visible.
&div class="tab-content"&
&div role="tabpanel" class="tab-pane fade in active" id="home"&...&/div&
&div role="tabpanel" class="tab-pane fade" id="profile"&...&/div&
&div role="tabpanel" class="tab-pane fade" id="messages"&...&/div&
&div role="tabpanel" class="tab-pane fade" id="settings"&...&/div&
Activates a tab element and content container. Tab should have either a data-target or an href targeting a container node in the DOM. In the above examples, the tabs are the &a&s with data-toggle="tab" attributes.
.tab('show')
Selects the given tab and shows its associated content. Any other tab that was previously selected becomes unselected and its associated content is hidden. Returns to the caller before the tab pane has actually been shown (i.e. before the shown.bs.tab event occurs).
$('#someTab').tab('show')
When showing a new tab, the events fire in the following order:
hide.bs.tab (on the current active tab)
show.bs.tab (on the to-be-shown tab)
hidden.bs.tab (on the previous active tab, the same one as for the hide.bs.tab event)
shown.bs.tab (on the newly-active just-shown tab, the same one as for the show.bs.tab event)
If no tab was already active, then the hide.bs.tab and hidden.bs.tab events will not be fired.
Event Type
Description
show.bs.tab
This event fires on tab show, but before the new tab has been shown. Use event.target and event.relatedTarget to target the active tab and the previous active tab (if available) respectively.
shown.bs.tab
This event fires on tab show after a tab has been shown. Use event.target and event.relatedTarget to target the active tab and the previous active tab (if available) respectively.
hide.bs.tab
This event fires when a new tab is to be shown (and thus the previous active tab is to be hidden). Use event.target and event.relatedTarget to target the current active tab and the new soon-to-be-active tab, respectively.
hidden.bs.tab
This event fires after a new tab is shown (and thus the previous active tab is hidden). Use event.target and event.relatedTarget to target the previous active tab and the new active tab, respectively.
$('a[data-toggle="tab"]').on('shown.bs.tab', function (e) {
e.target // newly activated tab
e.relatedTarget // previous active tab
Inspired by the excellent jQuery.tipsy plugin written by Jason F Tooltips are an updated version, which don't rely on images, use CSS3 for animations, and data-attributes for local title storage.
Tooltips with zero-length titles are never displayed.
Hover over the links below to see tooltips:
Tight pants next level keffiyeh
haven't heard of them. Photo booth beard raw denim letterpress vegan messenger bag stumptown. Farm-to-table seitan, mcsweeney's fixie sustainable quinoa 8-bit american apparel
terry richardson vinyl chambray. Beard stumptown, cardigans banh mi lomo thundercats. Tofu biodiesel williamsburg marfa, four loko mcsweeney's cleanse vegan chambray. A really ironic artisan , scenester farm-to-table banksy Austin
freegan cred raw denim single-origin coffee viral.
Static tooltip
Four options are available: top, right, bottom, and left aligned.
Tooltip on the left
Tooltip on the top
Tooltip on the bottom
Tooltip on the right
Four directions
Tooltip on left
Tooltip on top
Tooltip on bottom
Tooltip on right
&button type="button" class="btn btn-default" data-toggle="tooltip" data-placement="left" title="Tooltip on left"&Tooltip on left&/button&
&button type="button" class="btn btn-default" data-toggle="tooltip" data-placement="top" title="Tooltip on top"&Tooltip on top&/button&
&button type="button" class="btn btn-default" data-toggle="tooltip" data-placement="bottom" title="Tooltip on bottom"&Tooltip on bottom&/button&
&button type="button" class="btn btn-default" data-toggle="tooltip" data-placement="right" title="Tooltip on right"&Tooltip on right&/button&
Opt-in functionality
For performance reasons, the Tooltip and Popover data-apis are opt-in, meaning you must initialize them yourself.
One way to initialize all tooltips on a page would be to select them by their data-toggle attribute:
$(function () {
$('[data-toggle="tooltip"]').tooltip()
The tooltip plugin generates content and markup on demand, and by default places tooltips after their trigger element.
Trigger the tooltip via JavaScript:
$('#example').tooltip(options)
The required markup for a tooltip is only a data attribute and title on the HTML element you wish to have a tooltip. The generated markup of a tooltip is rather simple, though it does require a position (by default, set to top by the plugin).
&!-- HTML to write --&
&a href="#" data-toggle="tooltip" title="Some tooltip text!"&Hover over me&/a&
&!-- Generated markup by the plugin --&
&div class="tooltip top" role="tooltip"&
&div class="tooltip-arrow"&&/div&
&div class="tooltip-inner"&
Some tooltip text!
Multiple-line links
Sometimes you want to add a tooltip to a hyperlink that wraps multiple lines. The default behavior of the tooltip plugin is to center it horizontally and vertically. Add white-space: to your anchors to avoid this.
Tooltips in button groups, input groups, and tables require special setting
When using tooltips on elements within a .btn-group or an .input-group, or on table-related elements (&td&, &th&, &tr&, &thead&, &tbody&, &tfoot&), you'll have to specify the option container: 'body' (documented below) to avoid unwanted side effects (such as the element growing wider and/or losing its rounded corners when the tooltip is triggered).
Don't try to show tooltips on hidden elements
Invoking $(...).tooltip('show') when the target element is display: will cause the tooltip to be incorrectly positioned.
Accessible tooltips for keyboard and assistive technology users
For users navigating with a keyboard, and in particular users of assistive technologies, you should only add tooltips to keyboard-focusable elements such as links, form controls, or any arbitrary element with a tabindex="0" attribute.
Options can be passed via data attributes or JavaScript. For data attributes, append the option name to data-, as in data-animation="".
Description
Apply a CSS fade transition to the tooltip
string | false
Appends the tooltip to a specific element. Example: container: 'body'. This option is particularly useful in that it allows you to position the tooltip in the flow of the document
near the triggering element - which will prevent the tooltip from floating away from the triggering element during a window resize.
number | object
Delay showing and hiding the tooltip (ms) - does not apply to manual trigger type
If a number is supplied, delay is applied to both hide/show
Object structure is: delay: { "show": 500, "hide": 100 }
Insert HTML into the tooltip. If false, jQuery's text method will be used to insert content into the DOM. Use text if you're worried about XSS attacks.
string | function
How to position the tooltip - top | bottom | left | right | auto.When "auto" is specified, it will dynamically reorient the tooltip. For example, if placement is "auto left", the tooltip will display to the left when possible, otherwise it will display right.
When a function is used to determine the placement, it is called with the tooltip DOM node as its first argument and the triggering element DOM node as its second. The this context is set to the tooltip instance.
If a selector is provided, tooltip objects will be delegated to the specified targets. In practice, this is used to enable dynamic HTML content to have tooltips added. See
'&div class="tooltip" role="tooltip"&&div class="tooltip-arrow"&&/div&&div class="tooltip-inner"&&/div&&/div&'
Base HTML to use when creating the tooltip.
The tooltip's title will be injected into the .tooltip-inner.
.tooltip-arrow will become the tooltip's arrow.
The outermost wrapper element should have the .tooltip class.
string | function
Default title value if title attribute isn't present.
If a function is given, it will be called with its this reference set to the element that the tooltip is attached to.
'hover focus'
How tooltip is triggered - click | hover | focus | manual. You may pa separate them with a space. manual cannot be combined with any other trigger.
string | object | function
{ selector: 'body', padding: 0 }
Keeps the tooltip within the bounds of this element. Example: viewport: '#viewport' or { "selector": "#viewport", "padding": 0 }
If a function is given, it is called with the triggering element DOM node as its only argument. The this context is set to the tooltip instance.
$().tooltip(options)
Attaches a tooltip handler to an element collection.
.tooltip('show')
Reveals an element's tooltip. Returns to the caller before the tooltip has actually been shown (i.e. before the shown.bs.tooltip event occurs). This is considered a "manual" triggering of the tooltip. Tooltips with zero-length titles are never displayed.
$('#element').tooltip('show')
.tooltip('hide')
Hides an element's tooltip. Returns to the caller before the tooltip has actually been hidden (i.e. before the hidden.bs.tooltip event occurs). This is considered a "manual" triggering of the tooltip.
$('#element').tooltip('hide')
.tooltip('toggle')
Toggles an element's tooltip. Returns to the caller before the tooltip has actually been shown or hidden (i.e. before the shown.bs.tooltip or hidden.bs.tooltip event occurs). This is considered a "manual" triggering of the tooltip.
$('#element').tooltip('toggle')
.tooltip('destroy')
Hides and destroys an element's tooltip. Tooltips that use delegation (which are created using ) cannot be individually destroyed on descendant trigger elements.
$('#element').tooltip('destroy')
Event Type
Description
show.bs.tooltip
This event fires immediately when the show instance method is called.
shown.bs.tooltip
This event is fired when the tooltip has been made visible to the user (will wait for CSS transitions to complete).
hide.bs.tooltip
This event is fired immediately when the hide instance method has been called.
hidden.bs.tooltip
This event is fired when the tooltip has finished being hidden from the user (will wait for CSS transitions to complete).
inserted.bs.tooltip
This event is fired after the show.bs.tooltip event when the tooltip template has been added to the DOM.
$('#myTooltip').on('hidden.bs.tooltip', function () {
// do something…
为任意元素添加一小块浮层,就像 iPad 上一样,用于存放非主要信息。
弹出框的标题和内容的长度都是零的话将永远不会被显示出来。
弹出框依赖
,因此,如果你定制了 Bootstrap,一定要注意将依赖的插件编译进去。
由于性能的原因,工具提示和弹出框的 data 编程接口(data api)是必须要手动初始化的。
在一个页面上一次性初始化所有弹出框的方式是通过 data-toggle 属性选中他们:
$(function () {
$('[data-toggle="popover"]').popover()
Popovers in button groups, input groups, and tables require special setting
When using popovers on elements within a .btn-group or an .input-group, or on table-related elements (&td&, &th&, &tr&, &thead&, &tbody&, &tfoot&), you'll have to specify the option container: 'body' (documented below) to avoid unwanted side effects (such as the element growing wider and/or losing its rounded corners when the popover is triggered).
Don't try to show popovers on hidden elements
Invoking $(...).popover('show') when the target element is display: will cause the popover to be incorrectly positioned.
静态弹出框
4个可能的弹出方向:顶部、右侧、底部和左侧。
Popover 顶部
Sed posuere consectetur est at lobortis. Aenean eu leo quam. Pellentesque ornare sem lacinia quam venenatis vestibulum.
Popover 右侧
Sed posuere consectetur est at lobortis. Aenean eu leo quam. Pellentesque ornare sem lacinia quam venenatis vestibulum.
Popover 顶部
Sed posuere consectetur est at lobortis. Aenean eu leo quam. Pellentesque ornare sem lacinia quam venenatis vestibulum.
Popover 左侧
Sed posuere consectetur est at lobortis. Aenean eu leo quam. Pellentesque ornare sem lacinia quam venenatis vestibulum.
点我弹出/隐藏弹出框
&button type="button" class="btn btn-lg btn-danger" data-toggle="popover" title="Popover title" data-content="And here's some amazing content. It's very engaging. Right?"&点我弹出/隐藏弹出框&/button&
4个弹出方向
Popover on right
Popover on top
Popover on bottom
Popover on left
&button type="button" class="btn btn-default" data-container="body" data-toggle="popover" data-placement="left" data-content="Vivamus sagittis lacus vel augue laoreet rutrum faucibus."&
Popover on 左侧
&button type="button" class="btn btn-default" data-container="body" data-toggle="popover" data-placement="top" data-content="Vivamus sagittis lacus vel augue laoreet rutrum faucibus."&
Popover on 顶部
&button type="button" class="btn btn-default" data-container="body" data-toggle="popover" data-placement="bottom" data-content="Vivamus
sagittis lacus vel augue laoreet rutrum faucibus."&
Popover on 底部
&button type="button" class="btn btn-default" data-container="body" data-toggle="popover" data-placement="right" data-content="Vivamus sagittis lacus vel augue laoreet rutrum faucibus."&
Popover on 右侧
点击并让弹出框消失
通过使用 focus 触发器可以在用户点击弹出框是让其消失。
实现“点击并让弹出框消失”的效果需要一些额外的代码
为了更好的跨浏览器和跨平台效果,你必须使用 &a& 标签,不能使用 &button& 标签,并且,还必须包含 role="button" 和
&a tabindex="0" class="btn btn-lg btn-danger" role="button" data-toggle="popover" data-trigger="focus" title="Dismissible popover" data-content="And here's some amazing content. It's very engaging. Right?"&可消失的弹出框&/a&
通过 JavaScript 代码启动弹出框:
$('#example').popover(options)
可以通过 data 属性或 JavaScript 传递参数。对于 data 属性,将参数名附着到 data- 后面,例如 data-animation=""。
为弹出框赋予淡出的 CSS 动画效果。
string | false
Appends the popover to a specific element. Example: container: 'body'. This option is particularly useful in that it allows you to position the popover in the flow of the document near the triggering element - which will prevent the popover from floating away from the triggering element during a window resize.
string | function
Default content value if data-content attribute isn't present.
If a function is given, it will be called with its this reference set to the element that the popover is attached to.
number | object
Delay showing and hiding the popover (ms) - does not apply to manual trigger type
If a number is supplied, delay is applied to both hide/show
Object structure is: delay: { "show": 500, "hide": 100 }
Insert HTML into the popover. If false, jQuery's text method will be used to insert content into the DOM. Use text if you're worried about XSS attacks.
string | function
How to position the popover - top | bottom | left | right | auto.When "auto" is specified, it will dynamically reorient the popover. For example, if placement is "auto left", the popover will display to the left when possible, otherwise it will display right.
When a function is used to determine the placement, it is called with the popover DOM node as its first argument and the triggering element DOM node as its second. The this context is set to the popover instance.
If a selector is provided, popover objects will be delegated to the specified targets. In practice, this is used to enable dynamic HTML content to have popovers added. See
'&div class="popover" role="tooltip"&&div class="arrow"&&/div&&h3 class="popover-title"&&/h3&&div class="popover-content"&&/div&&/div&'
Base HTML to use when creating the popover.
The popover's title will be injected into the .popover-title.
The popover's content will be injected into the .popover-content.
.arrow will become the popover's arrow.
The outermost wrapper element should have the .popover class.
string | function
Default title value if title attribute isn't present.
If a function is given, it will be called with its this reference set to the element that the popover is attached to.
How popover is triggered - click | hover | focus | manual. You may pa separate them with a space. manual cannot be combined with any other trigger.
string | object | function
{ selector: 'body', padding: 0 }
Keeps the popover within the bounds of this element. Example: viewport: '#viewport' or { "selector": "#viewport", "padding": 0 }
If a function is given, it is called with the triggering element DOM node as its only argument. The this context is set to the popover instance.
$().popover(options)
Initializes popovers for an element collection.
.popover('show')
Reveals an element's popover. Returns to the caller before the popover has actually been shown (i.e. before the shown.bs.popover event occurs). This is considered a "manual" triggering of the popover. Popovers whose both title and content are zero-length are never displayed.
$('#element').popover('show')
.popover('hide')
Hides an element's popover. Returns to the caller before the popover has actually been hidden (i.e. before the hidden.bs.popover event occurs). This is considered a "manual" triggering of the popover.
$('#element').popover('hide')
.popover('toggle')
Toggles an element's popover. Returns to the caller before the popover has actually been shown or hidden (i.e. before the shown.bs.popover or hidden.bs.popover event occurs). This is considered a "manual" triggering of the popover.
$('#element').popover('toggle')
.popover('destroy')
Hides and destroys an element's popover. Popovers that use delegation (which are created using ) cannot be individually destroyed on descendant trigger elements.
$('#element').popover('destroy')
Event Type
Description
show.bs.popover
This event fires immediately when the show instance method is called.
shown.bs.popover
This event is fired when the popover has been made visible to the user (will wait for CSS transitions to complete).
hide.bs.popover
This event is fired immediately when the hide instance method has been called.
hidden.bs.popover
This event is fired when the popover has finished being hidden from the user (will wait for CSS transitions to complete).
inserted.bs.popover
This event is fired after the show.bs.popover event when the popover template has been added to the DOM.
$('#myPopover').on('hidden.bs.popover', function () {
// do something…
通过此插件可以为警告信息添加点击并消失的功能。
当使用 .close 按钮时,它必须是 .alert-dismissible 的第一个子元素,并且在它之前不能有任何文本内容。
Holy guacamole! Best check yo self, you're not looking too good.
Oh snap! You got an error!
Change this and that and try again. Duis mollis, est non commodo luctus, nisi erat porttitor ligula, eget lacinia odio sem nec elit. Cras mattis consectetur purus sit amet fermentum.
Take this action
Or do this
为关闭按钮添加 data-dismiss="alert" 属性就可以使其自动为警告框赋予关闭功能。关闭警告框也就是将其从 DOM 中删除。
&button type="button" class="close" data-dismiss="alert" aria-label="Close"&
&span aria-hidden="true"&&&/span&
为了让警告框在关闭时表现出动画效果,请确保为其添加了 .fade 和 .in 类。
$().alert()
让警告框监听具有 data-dismiss="alert" 属性的后裔元素的点击(click)事件。(如果是通过 data 属性进行的初始化则无需使用)
$().alert('close')
关闭警告框并从 DOM 中将其删除。如果警告框被赋予了 .fade 和 .in 类,那么,警告框在淡出之后才会被删除。
Bootstrap 的警告框插件对外暴露了一些可以被监听的事件。
close.bs.alert
当 close 方法被调用后立即触发此事件。
closed.bs.alert
当警告框被关闭后(也即 CSS 过渡效果完毕之后)立即触发此事件。
$('#myAlert').on('closed.bs.alert', function () {
// do something…
按钮的功能很丰富。通过控制按钮的状态或创建一组按钮并形成一些新的组件,例如工具条。
跨浏览器兼容性
。一个解决办法是设置 autocomplete="off"。参见 。
通过添加 data-loading-text="Loading..." 可以为按钮设置正在加载的状态。
从 v3.3.5 版本开始,此特性不再建议使用,并且已经在 v4 版本中删除了。
Loading state
&button type="button" id="myButton" data-loading-text="Loading..." class="btn btn-primary" autocomplete="off"&
Loading state
$('#myButton').on('click', function () {
var $btn = $(this).button('loading')
// business logic...
$btn.button('reset')
Single toggle
Add data-toggle="button" to activate toggling on a single button.
Pre-toggled buttons need .active and aria-pressed="true"
For pre-toggled buttons, you m}

我要回帖

更多关于 collapse.js下载 的文章

更多推荐

版权声明:文章内容来源于网络,版权归原作者所有,如有侵权请点击这里与我们联系,我们将及时删除。

点击添加站长微信