HTML不熟悉方法总结

1. onblur   属性在元素失去焦点时触发。

2. onfocus 属性在元素获得焦点时触发。

3.addEventlistener 事件监听

  监听键盘按下事件

 

componentDidMount(){
    document.addEventListener("keydown",this.handleEnterKey);
}

  handleEnterKey = (e) => {
    if(e.keyCode === 13){ // 按下回车键后触发登录函数
      this._login()  // 登录函数
    }
  }

 

 

 

 

4.focus() 方法用于给予该元素焦点。这样用户不必点击它,就能编辑显示的文本了。

5.Element.scrollIntoView() 方法让当前的元素滚动到浏览器窗口的可视区域内

 

 1 backTop() {
 2       if (document.documentElement) {
 3         document.documentElement.scrollIntoView({
 4           behavior: "smooth",
 5           block: "start",
 6           inline: "nearest"
 7         });
 8       } else {
 9         document.body.scrollIntoView({
10           behavior: "smooth",
11           block: "start",
12           inline: "nearest"
13         });
14       }
15     }

 

6. marquee 跑马灯标签

页面的自动滚动效果,可由javascript来实现,但是今天无意中发现了一个html标签 - <marquee></marquee>可以实现多种滚动效果,无需js控制。

使用marquee标记不仅可以移动文字,也可以移动图片,表格等.

语法:<marquee>...</marquee>; 说明:在标记之间添加要进行滚动的内容。

重要属性:

1.滚动方向direction(包括4个值:up、 down、 left和 right)

  语法:<marquee direction="滚动方向">...</marquee>

2.滚动方式behavior(scroll:循环滚动,默认效果; slide:只滚动一次就停止; alternate:来回交替进行滚动)

  语法:<marquee behavior="滚动方式">...</marquee>

3.滚动速度scrollamount(滚动速度是设置每次滚动时移动的长度,以像素为单位)

  语法:<marquee scrollamount="5">...</marquee>

4.滚动延迟scrolldelay(设置滚动的时间间隔,单位是毫秒)

  语法:<marquee scrolldelay="100">...</marquee>

5.滚动循环loop(默认值是-1,滚动会不断的循环下去)

  语法:<marquee loop="2">...</marquee>

6.滚动范围width、height

7.滚动背景颜色bgcolor

8.空白空间hspace、vspace

 代码示例:

 1 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
 2 <html xmlns="http://www.w3.org/1999/xhtml">
 3 <head>
 4 <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
 5 <title>无标题文档</title>
 6 </head>
 7 
 8 <body>
 9 <div>
10 <marquee direction="up" behavior="scroll" scrollamount="1" scrolldelay="0" loop="-1" width="1000" height="50" bgcolor="#0099FF" hspace="10" vspace="10">
11 指整个Marquee对齐方式; (2)behavior:设置滚动的方式: scroll:表示由一端滚动到另一端,会重复,缺陷是不能无缝滚动。 slide:表示由一段滚动到另一端,不会重复...
12 </marquee>
13 </div>
14 </body>
15 </html>

9.CSS 多余两行省略符号

.box-text{
  overflow: hidden;
  text-overflow: ellipsis;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  line-clamp: 2;
  -webkit-box-orient: vertical;
}

 

 10.防止图片宽度/高度 过大而产生拉伸效果  使用背景图片的 cover属性

<div style={{
     backgroundSize: 'cover',
     backgroundPosition: 'center center',
     width: autoWidth(150),
     height: autoWidth(80),
     backgroundImage: `url(${"https:" + String(item.photos).split(',')[0]})`
}} />

11.input标签 上传图片/文件上传

 html代码

<form>
  <input ref={(e)=>this._image = e} style={{opacity:0}} type="file" id='image' name="image" accept='image' onChange={(e)=>this.handleInputChange(e)} />
  <label htmlFor="image" style={{position:'absolute'}} className='photo_text'>(点击拍摄)</label>
</form>

js代码

// 全局对象,不同function使用传递数据
const imgFile = {};
 handleInputChange = (event) => {
    // 获取当前选中的文件
    const file = event.target.files[0];
    const imgMasSize = 1024 * 1024 * 10; // 10MB

    // 检查文件类型
    if(['jpeg', 'png', 'gif', 'jpg'].indexOf(file.type.split("/")[1]) < 0){
        // 自定义报错方式
        // Toast.error("文件类型仅支持 jpeg/png/gif!", 2000, undefined, false);
        return;
    }
  this._image.value = ''
    // 文件大小限制
    if(file.size > imgMasSize ) {
        // 文件大小自定义限制
        // Toast.error("文件大小不能超过10MB!", 2000, undefined, false);
        return;
    }

    // 判断是否是ios
    if(!!window.navigator.userAgent.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/)){
        // iOS
        this.transformFileToFormData(file);
        return;
    }

    // 图片压缩之旅
    this.transformFileToDataUrl(file);
}
// 将File append进 FormData
 transformFileToFormData (file) {
    const formData = new FormData();
    // 自定义formData中的内容
    // type
    formData.append('type', file.type);
    // size
    formData.append('size', file.size || "image/jpeg");
    // name
    formData.append('name', file.name);
    // lastModifiedDate
    formData.append('lastModifiedDate', file.lastModifiedDate);
    // append 文件
    formData.append('file', file);
    // 上传图片
    this.uploadImg(formData);
}
// 将file转成dataUrl
transformFileToDataUrl (file) { const imgCompassMaxSize = 200 * 1024; // 超过 200k 就压缩 // 存储文件相关信息 imgFile.type = file.type || 'image/jpeg'; // 部分安卓出现获取不到type的情况 imgFile.size = file.size; imgFile.name = file.name; imgFile.lastModifiedDate = file.lastModifiedDate; // 封装好的函数 const reader = new FileReader(); // file转dataUrl是个异步函数,要将代码写在回调里 reader.onload = function(e) { const result = e.target.result; if(result.length < imgCompassMaxSize) { compress(result, processData, false ); // 图片不压缩 } else { compress(result, processData); // 图片压缩 } }; reader.readAsDataURL(file); } // 使用canvas绘制图片并压缩

compress (dataURL, callback, shouldCompress = true) { const img = new window.Image(); img.src = dataURL; img.onload = function () { const canvas = document.createElement('canvas'); const ctx = canvas.getContext('2d'); canvas.width = img.width; canvas.height = img.height; ctx.drawImage(img, 0, 0, canvas.width, canvas.height); let compressedDataUrl; if(shouldCompress){ compressedDataUrl = canvas.toDataURL(imgFile.type, 0.2); } else { compressedDataUrl = canvas.toDataURL(imgFile.type, 1); } callback(compressedDataUrl); } }
processData (dataURL) {
// 这里使用二进制方式处理dataUrl const binaryString = window.atob(dataUrl.split(',')[1]); const arrayBuffer = new ArrayBuffer(binaryString.length); const intArray = new Uint8Array(arrayBuffer); const imgFile = this.imgFile; for (let i = 0, j = binaryString.length; i < j; i++) { intArray[i] = binaryString.charCodeAt(i); } const data = [intArray]; let blob; try { blob = new Blob(data, { type: imgFile.type }); } catch (error) { window.BlobBuilder = window.BlobBuilder || window.WebKitBlobBuilder || window.MozBlobBuilder || window.MSBlobBuilder; if (error.name === 'TypeError' && window.BlobBuilder){ const builder = new BlobBuilder(); builder.append(arrayBuffer); blob = builder.getBlob(imgFile.type); } else { // Toast.error("版本过低,不支持上传图片", 2000, undefined, false); throw new Error('版本过低,不支持上传图片'); } } // blob 转file const fileOfBlob = new File([blob], imgFile.name); const formData = new FormData(); // type formData.append('type', imgFile.type); // size formData.append('size', fileOfBlob.size); // name formData.append('name', imgFile.name); // lastModifiedDate formData.append('lastModifiedDate', imgFile.lastModifiedDate); // append 文件 formData.append('file', fileOfBlob); this.uploadImg(formData); } // 上传图片 uploadImg (formData) { const xhr = new XMLHttpRequest(); // 进度监听 xhr.upload.addEventListener('progress', (e)=>{console.log(e.loaded / e.total)}, false); // 加载监听 // xhr.addEventListener('load', ()=>{console.log("加载中");}, false); // 错误监听 xhr.addEventListener('error', ()=>{Toast.error("上传失败!", 2000, undefined, false);}, false); xhr.onreadystatechange = () => { if (xhr.readyState === 4) { const result = JSON.parse(xhr.responseText); if (xhr.status === 200) { // 上传成功 } else { // 上传失败 } } }; xhr.open('POST', '/uploadUrl' , true); xhr.send(formData); }

 12.jquery 渲染JSON数据/数组对象数据

    const  data = [
        {
        title:'保险1',
        detail:'承包....',
        price:88
        },
        {
            title:'保险2',
            detail:'承包...',
            price:45
        },
    ]

    let str="<ul class='package-gift'>";
    $.each(data,function(index, item){
        str+="<li style='margin-bottom: 10px;'><div class='package-common-title'><img src='asset/unchecked.png' alt=''><p>"+item.title+"</p></div>";
        str+="<p class='package-gift-detail'>"+item.detail+"</p>";
        str+="<div class='package-gift-price'><span>原价</span><span>¥</span><span>" + item.price +"</span></div></li>";
    });
    str+="</ul>";

    $(".package-gift-section").append(str);

13.fixed 页面滚动

{
position:fixed;
overflow:scroll;
bottom:0;
top:0;
}

14.jquery 多重遍历 + 元素替换  实现了点击A 替换 B 和C ,其中C为列表

 

packageList代码 

[{"id":1,"title":"电信花卡19元","tag":"流量多多 畅玩不停","content":"200GB专属流量;免费接听; 100分\n","icon":"https://image.baidu.com/search/detail?ct=503316480\u0026z=\u0026tn=baiduimagedetail\u0026ipn=d\u0026word=%E5%9B%BE%E6%A0%87%20icon\u0026step_word=\u0026ie=utf-8\u0026in=\u0026cl=2\u0026lm=-1\u0026st=-1\u0026hd=undefined\u0026latest=undefined\u0026copyright=undefined\u0026cs=2258620003,138289266\u0026os=3769280324,3390709901\u0026simid=3363682034,337277918\u0026pn=2\u0026rn=1\u0026di=137390\u0026ln=1537\u0026fr=\u0026fmq=1389861203899_R\u0026fm=\u0026ic=0\u0026s=undefined\u0026se=\u0026sme=\u0026tab=0\u0026width=\u0026height=\u0026face=undefined\u0026is=0,0\u0026istype=2\u0026ist=\u0026jit=\u0026bdtype=0\u0026spn=0\u0026pi=0\u0026gsm=0\u0026hs=2\u0026oriquery=%E5%9B%BE%E6%A0%87\u0026objurl=http%3A%2F%2Fhbimg.b0.upaiyun.com%2F1f409a2915794183044b9b6f5a733ef3c6b483af6e61-vsvFa3_fw658\u0026rpstart=0\u0026rpnum=0\u0026adpicid=0\u0026force=undefined","give_away":[{"id":1,"title":"中国平安保险E生平安·重疾险","content":"承保100种高发疾病,确诊即可赔付","original_price":"90.00000000000000000000","contract_id":1},{"id":2,"title":"中国平安保险E生平安·重疾险","content":"承保100种高发疾病,确诊即可赔付","original_price":"90.00000000000000000000","contract_id":1}],"actual_price":"19.00000000000000000000"},{"id":3,"title":"电信花卡129元","tag":"赠送宽带 飞速上网","content":"200GB专属流量;免费接听; 100分 ","icon":"https://image.baidu.com/search/detail?ct=503316480\u0026z=\u0026tn=baiduimagedetail\u0026ipn=d\u0026word=%E5%9B%BE%E6%A0%87%20icon\u0026step_word=\u0026ie=utf-8\u0026in=\u0026cl=2\u0026lm=-1\u0026st=-1\u0026hd=undefined\u0026latest=undefined\u0026copyright=undefined\u0026cs=1624956854,2683166289\u0026os=428664698,3137670526\u0026simid=4182229141,534921667\u0026pn=29\u0026rn=1\u0026di=81840\u0026ln=1537\u0026fr=\u0026fmq=1389861203899_R\u0026fm=\u0026ic=0\u0026s=undefined\u0026se=\u0026sme=\u0026tab=0\u0026width=\u0026height=\u0026face=undefined\u0026is=0,0\u0026istype=2\u0026ist=\u0026jit=\u0026bdtype=0\u0026spn=0\u0026pi=0\u0026gsm=0\u0026hs=2\u0026oriquery=%E5%9B%BE%E6%A0%87\u0026objurl=http%3A%2F%2Fhbimg.b0.upaiyun.com%2F92e4826b11ec121e35c0d3bf62c1709b0f730e62289d-o8V8fR_fw658\u0026rpstart=0\u0026rpnum=0\u0026adpicid=0\u0026force=undefined","give_away":[],"actual_price":"129.00000000000000000000"},{"id":2,"title":"电信花卡59元","tag":"流量多多 无限畅玩","content":"200GB专属流量;免费接听; 100分 ","icon":"https://image.baidu.com/search/detail?ct=503316480\u0026z=\u0026tn=baiduimagedetail\u0026ipn=d\u0026word=%E5%9B%BE%E6%A0%87%20icon\u0026step_word=\u0026ie=utf-8\u0026in=\u0026cl=2\u0026lm=-1\u0026st=-1\u0026hd=undefined\u0026latest=undefined\u0026copyright=undefined\u0026cs=2973854516,307071732\u0026os=706910135,3868125202\u0026simid=3374560104,335918967\u0026pn=21\u0026rn=1\u0026di=78540\u0026ln=1537\u0026fr=\u0026fmq=1389861203899_R\u0026fm=\u0026ic=0\u0026s=undefined\u0026se=\u0026sme=\u0026tab=0\u0026width=\u0026height=\u0026face=undefined\u0026is=0,0\u0026istype=2\u0026ist=\u0026jit=\u0026bdtype=0\u0026spn=0\u0026pi=0\u0026gsm=0\u0026hs=2\u0026oriquery=%E5%9B%BE%E6%A0%87\u0026objurl=http%3A%2F%2Fhbimg.b0.upaiyun.com%2Fc9d50569eb0d9decf3afa0c3982b1f966bc83b7f59af0-BPVUzU_fw658\u0026rpstart=0\u0026rpnum=0\u0026adpicid=0\u0026force=undefined","give_away":[],"actual_price":"59.00000000000000000000"}]
packageList 代码

 

 

          function getGift(item,giftData){
                        giftStr = "<ul class='package-gift'>";
                        $.each(giftData,function(item,value){
                            giftStr+="<li style='margin-bottom: 20px;'><div class='package-common-title' ><img src='asset/unchecked.png' alt=''><p style='color: #000;'>"+value.title+"</p></div>";
                            giftStr+="<p class='package-gift-detail'>"+value.content+"</p>";
                            giftStr+="<div class='package-gift-price'><span>原价</span><span>¥</span><span>" + Number(value.original_price) +"</span></div></li>";
                        });
                        console.log(item,giftStr)
                        return giftStr
                    }


                    $.each(packageList,function (item,value) {
                        console.log('让我康康',packageList)
                        giftList.push(value.give_away)
                        expensesList.push({content:value.content,title:value.title})
                        packageListStr += "<li><div class='package-order '><p class='package-order-txt'>" + (item + 1) +"</p></div>"
                        packageListStr += "<img class='package-func'  src="+ value.icon +" ><p class='package-title'>"+ value.title +"</p><p class='package-subtitle'>" + value.tag +"</p><div class='package-info-section'> <div class='package-common-title'><p>"
                            + value.title +"</p></div><table class='package-info-box'><tr><th>套餐包含</th><td>" + value.content + "</td></tr><tr><th>套外包含</th><td>" + value.content +"</td></tr></table></div>"+
                            getGift(item,value.give_away)  +  "</ul></li>"
                    });

                    packageListStr += "</ul>";

                    $('.package-check-section').append(packageListStr);

替换元素代码

                    //初始化套餐详情
                    $('.package-section').html($('.package-check li').eq(0).find('.package-info-section').prop('outerHTML'))
                    $('.package-section .package-info-section').removeClass('hidden')

                    //初始化赠品
                    $('.package-gift-section').html($('.package-check li').eq(0).find('.package-gift').prop('outerHTML'))
                    $('.package-gift-section .package-gift').removeClass('hidden')

                    // 选择套餐修改套餐详情
                    $('.package-check li').on('click',function () {
                        const idx = $(this).index();
                        $('.package-info>li').eq(idx).show()
                        $('.package-info>li').eq(idx).siblings().hide()
                        console.log($('.package-gift-section li'),'不删')
                        // $(this).siblings().find('.package-info-section').addClass('hidden')
                        $('.package-section').html($(this).find('.package-info-section').prop('outerHTML'))   //这里的prop('outerHTML')包括了自己这个标签 以及里面的内容
                        $('.package-section .package-info-section').removeClass('hidden');
                        $('.package-gift-section').html($(this).find('.package-gift').prop('outerHTML'))
                        $('.package-gift-section .package-gift').removeClass('hidden');
                    });

 

 

 因为 59元 129元套餐的赠品data为[] 所以只有19元套餐有赠品

 

 15. bootstrap + jquery 渲染动态表格

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <link rel="stylesheet" href="./bootstrap.css">
  <title>BootStrap jQuery 渲染动态表格</title>
</head>
<body>
  <table style="width:100%;text-align:center;margin:30px 10px 10px 10px;border:1px solid #E3E3E3" border="1" cellspacing="10" id="tabData" class="tab table-striped table-hover">
    <thead style="background-color:#299ef5">
        <tr style="color:white">
            <td rowspan="2" style="width:10%;height:60px;">排名</td>
            <td rowspan="2" style="width:15%">区域</td>
            <td colspan="3" style="width:25%;height:30px;">综合能耗</td>
            <td colspan="3" style="width:25%">总产值</td>
            <td colspan="3" style="width:25%">万元产值能耗</td>
        </tr>
        <tr style="color:white">
            <td style="height:30px;">本期</td>
            <td>同期</td>
            <td>增幅</td>
            <td>本期</td>
            <td>同期</td>
            <td>增幅</td>
            <td>本期</td>
            <td>同期</td>
            <td>增幅</td>
        </tr>
    </thead>
    <tbody></tbody>
</table>
</body>
<script src="./jquery.js"></script>
<script>
//加载表格内容
$(function (params) {

  function initTable() {
    var temp = "";
    var body = "";
    const data = [
      {ZoneName:1, EneryConsumeNow:2,EneryConsumeBefore:3, ECRiseRate:4, TotalOutputNow:5, TotalOutputBefore:6, TORiseRate:7, AverageNow:8, AverageBefore:9, RiseRate:10},
      {ZoneName:10, EneryConsumeNow:20, EneryConsumeBefore:30, ECRiseRate:40, TotalOutputNow:50, TotalOutputBefore:60, TORiseRate:70, AverageNow:80, AverageBefore:90, RiseRate:100}
    ]
    for (var i = 0; i < data.length; i++){
        var temp = "<tr style='height:30px;'><td>" + (i + 1) + "</td><td>"
            + data[i].ZoneName + "</td><td>"
            + data[i].EneryConsumeNow + "</td><td>"
            + data[i].EneryConsumeBefore + "</td><td>"
            + data[i].ECRiseRate + "</td><td>"
            + data[i].TotalOutputNow + "</td><td>"
            + data[i].TotalOutputBefore + "</td><td>"
            + data[i].TORiseRate + "</td><td>"
            + data[i].AverageNow + "</td><td>"
            + data[i].AverageBefore + "</td><td>"
            + data[i].RiseRate + "</td></tr>" + "/n";
        body += temp;
    }
    $("#tabData tbody").html("");  //清空
    $("#tabData tbody").html(body);
  }
initTable();

})

</script>
</html>

 

 

extra :

1. input 文件上传时,不能连续上传同一个文件,因为浏览器会判断文件路径,所有要使文件路径清空

 this._image.value=''

2.点击时间触发input中的文件上传事件后,出现了位置偏移(位移)

是因为input标签没有设置宽度导致的,将它的宽度设为0即可。

  

posted @ 2019-04-05 23:23  一路向北√  阅读(271)  评论(0编辑  收藏  举报

web应用开发&研究 -

业精于勤而荒于嬉。

工作,使我快乐。


Font Awesome | Respond.js | Bootstrap中文网