文本属性类相关操作
一 概念
1、文本
```
html([val|fn])
text([val|fn])
val([val|fn|arr])
```
2、属性
```
attr(name|pro|key,val|fn)
removeAttr(name)
prop(n|p|k,v|f)
removeProp(name)
```
3、类
```
addClass(class|fn)
removeClass([class|fn])
toggleClass(class|fn[,sw])
```
二 代码示范
<!DOCTYPE html>
<html lang="zh">
<head>
<meta charset="UTF-8">
<title>文本属性类相关操作</title>
<style type="text/css">
div {
background-color: red;
}
/*jq内部已经操作*/
/*[hidden] {
display: none;
}*/
div.active {
background-color: cyan!important;
}
</style>
</head>
<body hidden>
<div class="div">12345</div>
<input type="text">
<a href="">前往百度</a>
</body>
<script src="js/jquery-3.3.1.js"></script>
<!-- 内容 -->
<script type="text/javascript">
$(function () {
var $div = $('div');
console.log($div);
// text操作
console.log($div.text()); // 无参就是获取原有的文本
// $div.text('上山打老虎'); // 有参就是对文本的修改
// 追加文本
// 1.
// $div.text($div.text() + '上山打老虎');
// 2.
$div.text(function (index, old) {
var target = '上山打老虎';
return old + target;
})
// html操作
$div.html("<b>天下第一衰,转运!!!</b>");
// val操作
$('input').val("霉运");
// 失去焦点事件
$(':input').on('blur', function () {
console.log($(this).val());
})
})
</script>
<!-- 样式 -->
<script type="text/javascript">
$(function () {
// 赋值: 链式赋值
$('div').css("width", "200px").css("height", "200px");
// 取值: 行间式 | 计算后样式
console.log($('div').css("width"));
console.log($('div').css("background-color"));
// 对象赋值
$('div').css({
width: 300, // 默认添加单位
height: "300px",
"background-color": "pink", // key为css连接语法,js不支持这样的标识符,用字符串形式表示
borderRadius: '50%' // 小驼峰命名
})
$('div').css({
width: "300px",
height: "300px",
backgroundColor: "pink",
borderRadius: '50%'
})
// 回调函数形式
})
</script>
<!-- 属性 -->
<script type="text/javascript">
$(function () {
// 解决jq加载过程中,页面出现样式变化导致的闪烁问题
$('body').removeAttr('hidden');
$('a').attr("href", "https://www.baidu.com");
})
</script>
<!-- 类 -->
<script type="text/javascript">
$(function () {
$('div').on("mouseover", function () {
console.log(123);
$(this).addClass("active"); // 追加一个新类名
})
$('div').on("mouseout", function () {
$(this).removeClass("active"); // 删除指定类名
})
$('div').on("click", function () {
$(this).toggleClass("active"); // 切换类名
})
})
</script>
</html>

浙公网安备 33010602011771号