博客列表 >为留言板添加字数实时统计与禁止超出功能; 2. 自选一些字符串和数组方法进行实例演示

为留言板添加字数实时统计与禁止超出功能; 2. 自选一些字符串和数组方法进行实例演示

杰西卡妈妈
杰西卡妈妈原创
2021年04月20日 04:05:56567浏览

1. 留言板添加字数与限制字符

  • 写留言板

    <style>
    {
    margin: 0;
    padding: 0;
    box-sizing: border-box;
    }
    li {
    list-style: none;
    }
    body {
    background-color:rgb(174, 236, 236);
    color: #555;

    }
    .comment {
    width: 85%;
    margin: 1em auto;

    display: grid;
    gap: 0.5em;
    }
    .comment #content {
    resize: none;
    border:none;
    padding: 0.5em;
    outline: none;
    }
    .comment #content:focus,
    .comment #content:hover {

    box-shadow: 0 0 8px steelblue;
    transition: 0.6s;
    }
    .comment .submit {
    width: 30%;
    margin-left: auto;
    background-color: lightseagreen;
    border: none;
    outline: none;
    color: white;
    height: 2.5em;
    }
    .comment .submit:hover {
    background-color: seagreen;
    transition: 0.6s;
    cursor: pointer;
    }
    .list {

    width: 80%;
    /
    background-color: yellow; /
    margin: auto;
    padding: 1em;
    }

    .del-btn {
    background-color: wheat;
    color: red;
    padding:0.5em 1em;
    /
    height: 2.2em; */
    border:none;
    outline: none;
    }
    .del-btn:hover {
    cursor: pointer;
    background-color: lime;
    }

    </style>

  • 获取元素

    <script>
    1. const comment = document.querySelector('.comment');
    2. const content = comment.content;
    3. const submitBtn = comment.submit;
    4. const commentList = document.querySelector('.list');
  • 添加字数,限制字符,新留言前置

    submitBtn.onclick = (ev) => {

    1. let value = content.value.trim();
    2. if (value.length > 0 && value.length <= 100) {
    3. const newComment = document.createElement("li");
    4. newComment.textContent = value;
    5. newComment.style.borderBottom = "1px solid white";
    6. newComment.style.minHeight = "3em";
  • 新留言前置,留言成功

    commentList.prepend(newComment);

    1. alert("left message successful");
  • 清空留言,无内容或超字数

    content.value = null;
    1. content.focus();
    2. } else {
    3. alert("no content or too many words");
    4. content.focus();
    5. return false;
    6. }
    7. };
  • 添加删除留言button

    newComment.append(deleteBtn);
    const deleteBtn = document.createElement(“button”);
    deleteBtn.textContent = “delete”;
    deleteBtn.style.float = “right”;
    deleteBtn.classList.add(“del-btn”);
  • 确定是否删除

    deleteBtn.onclick = function () {
    if (confirm(“are you sure delete”)) {
    1. this.parentNode.remove();
    2. alert("delete successful");
    3. content.focus();
    4. return false;
    5. }
    6. };

2. 字符串和数组

  1. concat()拼装
  2. slice(start, end)取子串
  3. substr(start, size): 取子串
  4. trim(): 删除字符串二边的空白字符
  5. 将字符串打散成数组
声明:本文内容转载自脚本之家,由网友自发贡献,版权归原作者所有,如您发现涉嫌抄袭侵权,请联系admin@php.cn 核实处理。
全部评论
文明上网理性发言,请遵守新闻评论服务协议