持续创作,加速成长!这是我参与「掘金日新计划 · 10 月更文挑战」的第2天 ,点击查看活动详情
最近小颖接了个私活,客户要求用jquery和bootstrap来实现业务需求,小颖总结了下在写的过程中的一下坑,来记录一下
1.动态加载html文件
switch (_domName) {
case 'firstMenu':
// 首页
$("main").load('home.html');
break
case 'secondMenu':
// 下拉菜单
$("main").load("dropdown.html");
break
case 'thirdMenu':
// 工具提示框
$("main").load("tooltips.html");
break
}
2.使用 $(document).load("dropdown.html"); 动态加载的元素,要给其子元素添加点击事件时使用以下方法是不可行的:
$('img.open_voice').click(function(){
})
需使用以下方法才能绑定其点击事件:
方法一:
$("main").delegate("img.open_voice", "click", function () { //delegate给后加的节点绑定事件
});
方法二:
$(document).on("click", "img.open_voice", function () { //给后加的节点绑定事件
alert(111111)
});
3.语音播报文字、暂停播报
function soundSpeak(text) {
const msg = new SpeechSynthesisUtterance();
msg.text = text; //播放文案
msg.volume = '1'; // 声音的音量,区间范围是0到1,默认是1。
msg.rate = '1'; // 语速,数值,默认值是1,范围是0.1到10,表示语速的倍数,例如2表示正常语速的两倍。
msg.pitch = '0'; // 表示说话的音高,数值,范围从0(最小)到2(最大)。默认值为1。
msg.lang = 'zh-cn'; // 使用的语言,字符串, 例如:"zh-cn"
return msg;
}
var sound = window.speechSynthesis; // 定义局部变量
//播放
function playText(text) {
sound.speak(soundSpeak(text));
}
//停止
function stopSpeak() {
$('.open_voice').removeClass('active');
$('.open_voice').attr("src", 'img/horn.png');
sound.cancel();
}
当切换菜单时需判断当前是否在播放
if (sound.speaking) {
stopSpeak();
}
点击播放图标开始播放文字并切换图标
// 语音播放文字
$("main").delegate("img.open_voice", "click", function () { //delegate给后加的节点绑定事件
if ($(this).hasClass('active')) {
stopSpeak();
} else {
$(this).addClass('active');
$(this).attr("src", 'img/horn_close.png');
playText($('.txt-box').text());
}
});
默认:
点击后:
再次点击后图标变成默认状态
4.bootstrap 导航切换标记当前菜单
// 切换一级菜单
$('p.nav-link').click(function () {
var _childMenu = $('.dropdown-item.menu-child.active').attr('name');
var _domName = $(this).attr('name');
// 切换菜单时移除上一个菜单的子菜单选中类名
if (_childMenu && _domName && _childMenu != _domName) {
$('.dropdown-item.menu-child').removeClass('active');
}
$('p.nav-link.active').removeClass('active');
$(this).addClass('active');
if (sound.speaking) {
stopSpeak();
}
switch (_domName) {
case 'firstMenu':
// 首页
$("main").load('home.html');
break
case 'secondMenu':
// 下拉菜单
$("main").load("dropdown.html");
break
case 'thirdMenu':
// 工具提示框
$("main").load("tooltips.html");
break
}
});
5.bootstrap工具提示框显、隐
点自己显示,点其他地方隐藏
$('body').click(function () {
$("[data-toggle='popover']").popover('hide');
})
// 提示框点击事件
$("main").delegate(".tooltips-box span", "click", function (e) {
e.stopPropagation();
$('.tooltips-box span').removeClass('active_toggle');
$(this).addClass('active_toggle');
$("[data-toggle='popover']").popover('hide');
$(this).popover('show');
})
小颖原文博客地址: jquery+bootstrap学习笔记 代码:jquery+bootstrap