首页 > 其他分享 >2024-05-08 js 常见案例

2024-05-08 js 常见案例

时间:2024-05-08 22:55:35浏览次数:9  
标签:function 选项卡 05 08 js window var document display

1.表单验证

function validateForm() {  
    var name = document.forms["myForm"]["name"].value;  
    if (name == "") {  
        alert("Name must be filled out");  
        return false;  
    }  
    // 更多的验证...  
    return true;  
}

2.DOM 操作

var element = document.getElementById("myElement");  
element.textContent = "Hello, World!";  
element.style.color = "blue";

3.事件监听

var button = document.getElementById("myButton");  
button.addEventListener("click", function() {  
    alert("Button clicked!");  
});

4.创建元素

var newDiv = document.createElement("div");  
newDiv.textContent = "New div created!";  
document.body.appendChild(newDiv);

5.定时器

var count = 0;  
var timer = setInterval(function() {  
    console.log(count);  
    count++;  
    if (count >= 10) {  
        clearInterval(timer);  
    }  
}, 1000);

6.获取 URL 参数'

function getURLParameter(name) {  
    var url = window.location.href;  
    name = name.replace(/[\[\]]/g, '\\$&');  
    var regex = new RegExp('[?&]' + name + '(=([^&#]*)|&|#|$)');  
    var results = regex.exec(url);  
    if (!results) return null;  
    if (!results[2]) return '';  
    return decodeURIComponent(results[2].replace(/\+/g, ' '));  
}

7.AJAX 请求

var xhr = new XMLHttpRequest();  
xhr.open("GET", "https://api.example.com/data", true);  
xhr.onreadystatechange = function () {  
    if (xhr.readyState == 4 && xhr.status == 200) {  
        console.log(xhr.responseText);  
    }  
};  
xhr.send();

8.Cookie 操作

function setCookie(name, value, days) {  
    var expires = "";  
    if (days) {  
        var date = new Date();  
        date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));  
        expires = "; expires=" + date.toUTCString();  
    }  
    document.cookie = name + "=" + (value || "") + expires + "; path=/";  
}  

function getCookie(name) {  
    var nameEQ = name + "=";  
    var ca = document.cookie.split(';');  
    for (var i = 0; i < ca.length; i++) {  
        var c = ca[i];  
        while (c.charAt(0) == ' ') c = c.substring(1, c.length);  
        if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length, c.length);  
    }  
    return null;  
}

9.拖拽元素

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>拖拽元素</title>
    <style>
      body {
        margin: 0;
      }
      #draggable {
        width: 100px;
        height: 100px;
        background-color: #1890ff;
        position: relative;
        cursor: pointer;
      }
    </style>
  </head>
  <body>
    <div id="draggable"></div>
  </body>
</html>
<script>
  // 获取需要拖拽的元素
  var draggableElement = document.getElementById("draggable");

  // 拖拽相关的变量
  var isDragging = false;
  var currentX, currentY, initialX, initialY, offsetX, offsetY;

  // 监听mousedown事件
  draggableElement.onmousedown = function (e) {
    // 防止默认行为(例如,文本选择)
    e.preventDefault();

    // 标记为拖拽中
    isDragging = true;

    // 计算鼠标指针相对于元素的初始位置
    offsetX = e.clientX - draggableElement.getBoundingClientRect().left;
    offsetY = e.clientY - draggableElement.getBoundingClientRect().top;

    // 获取元素当前的偏移量
    initialX = parseInt(
      window.getComputedStyle(draggableElement).getPropertyValue("left") || "0",
      10
    );
    initialY = parseInt(
      window.getComputedStyle(draggableElement).getPropertyValue("top") || "0",
      10
    );

    // 添加mousemove和mouseup事件的监听器到window对象上,这样即使鼠标移动到了元素外部也能继续拖拽
    window.addEventListener("mousemove", onm ouseMove);
    window.addEventListener("mouseup", onm ouseUp);
  };

  // 监听mousemove事件
  function onm ouseMove(e) {
    if (!isDragging) return;

    // 计算新的位置
    currentX = e.clientX - offsetX;
    currentY = e.clientY - offsetY;

    // 限制拖拽的范围(可选)
    // 例如,限制在视口内
    currentX = Math.max(
      0,
      Math.min(currentX, window.innerWidth - draggableElement.offsetWidth)
    );
    currentY = Math.max(
      0,
      Math.min(currentY, window.innerHeight - draggableElement.offsetHeight)
    );

    // 更新元素的位置
    draggableElement.style.left = currentX + "px";
    draggableElement.style.top = currentY + "px";
  }

  // 监听mouseup事件
  function onm ouseUp(e) {
    // 标记拖拽结束
    isDragging = false;

    // 移除mousemove和mouseup事件的监听器
    window.removeEventListener("mousemove", onm ouseMove);
    window.removeEventListener("mouseup", onm ouseUp);
  }
</script>

10.滚动条监听

// 监听滚动事件  
window.addEventListener('scroll', function(event) {  
  // 获取滚动条的垂直位置  
  var scrollTop = window.pageYOffset || document.documentElement.scrollTop;  
    
  // 获取滚动条的水平位置(在需要的情况下)  
  var scrollLeft = window.pageXOffset || document.documentElement.scrollLeft;  
    
  // 输出滚动条的位置  
  console.log('x轴:' + scrollTop);  
  console.log('y轴:' + scrollLeft);  
});

11.1 选项卡(纯css版):label触发点击控制type=radio的input显示与隐藏

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
    <style>
      /* 隐藏所有选项卡内容 */
      .tab-content .tab {
        display: none;
      }

      /* 选中radio时显示对应的选项卡内容 */
      #tab1:checked ~ .tab-content #content1,
      #tab2:checked ~ .tab-content #content2,
      #tab3:checked ~ .tab-content #content3 {
        display: block;
      }

      /* 样式化选项卡按钮 */
      .tabs input[type="radio"] {
        display: none; /* 隐藏radio input */
      }

      .tabs label {
        display: inline-block;
        margin-right: 10px;
        padding: 5px 10px;
        border: 1px solid #ccc;
        cursor: pointer;
      }

      /* 选中状态的选项卡按钮样式 */
      .tabs input[type="radio"]:checked + label {
        background-color: #eee;
        border-bottom: 1px solid #fff; /* 防止底部出现双重边框 */
      }

      /* 其他可选样式 */
      .tab-content {
        margin-top: 20px; /* 选项卡内容与选项卡按钮之间的间距 */
      }

      /* 根据需要添加更多样式 */
    </style>
  </head>
  <body>
    <div class="tabs">
      <input type="radio" id="tab1" name="tabs" checked />
      <label for="tab1">选项卡1</label>
      <input type="radio" id="tab2" name="tabs" />
      <label for="tab2">选项卡2</label>
      <input type="radio" id="tab3" name="tabs" />
      <label for="tab3">选项卡3</label>

      <div class="tab-content">
        <div class="tab" id="content1">
          <p>这是选项卡1的内容。</p>
        </div>
        <div class="tab" id="content2">
          <p>这是选项卡2的内容。</p>
        </div>
        <div class="tab" id="content3">
          <p>这是选项卡3的内容。</p>
        </div>
      </div>
    </div>
  </body>
</html>

11.2.选项卡(js版)

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
    <style>
      .tab-link {
        cursor: pointer;
      }

      .tab-content {
        display: none;
      }

      .tab-content.active {
        display: block;
      }
    </style>
  </head>
  <body>
    <div class="tabs">
      <button class="tab-link" data-tab="tab1">选项卡1</button>
      <button class="tab-link" data-tab="tab2">选项卡2</button>
      <button class="tab-link" data-tab="tab3">选项卡3</button>

      <div class="tab-content" id="tab1">这是选项卡1的内容</div>
      <div class="tab-content" id="tab2">这是选项卡2的内容</div>
      <div class="tab-content" id="tab3">这是选项卡3的内容</div>
    </div>
  </body>
</html>
<script>
  // 获取所有的选项卡链接和内容
  const tabLinks = document.querySelectorAll(".tab-link");
  const tabContents = document.querySelectorAll(".tab-content");

  // 为每个选项卡链接添加点击事件监听器
  tabLinks.forEach(function (tabLink) {
    tabLink.addEventListener("click", function () {
      // 移除所有内容块的激活状态
      tabContents.forEach(function (tabContent) {
        tabContent.classList.remove("active");
      });

      // 激活对应的选项卡内容
      const tabToShow = document.getElementById(tabLink.dataset.tab);
      if (tabToShow) {
        tabToShow.classList.add("active");
      }
    });
  });

  // 如果有的话,激活第一个选项卡的内容
  if (tabContents[0]) {
    tabContents[0].classList.add("active");
  }
</script>

12.轮播图

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
    <style>
      .carousel {
        position: relative;
        width: 500px;
        height: 500px;
        margin: 50px auto 0;
        border: 1px solid #f2f2f2;
      }
      .carousel-images {
        display: flex;
        transition: transform 0.5s ease;
      }

      .carousel-images img {
        width: 500px;
      }

      /* 隐藏除第一张外的所有图片 */
      .carousel-images img:not(:first-child) {
        display: none;
      }
      .prev,
      .next {
        width: 50px;
        height: 50px;
        position: absolute;
        top: 50%;
        background-color: rgba(0, 0, 0, 0.5);
        color: #fff;
        border-radius: 50%;
        text-align: center;
        font-size: 32px;
        line-height: 50px;
        cursor: pointer;
      }
      .prev {
        left: 10px;
      }
      .next {
        right: 10px;
      }
    </style>
  </head>
  <body>
    <div class="carousel">
      <div class="carousel-images">
        <img
          src="https://www.foodiesfeed.com/wp-content/uploads/2023/08/grilled-crispy-pork-with-rice.jpg"
          alt="Image 1"
        />
        <img
          src="https://www.foodiesfeed.com/wp-content/uploads/2023/12/seafood-soup.jpg"
          alt="Image 2"
        />
        <img
          src="https://www.foodiesfeed.com/wp-content/uploads/2023/04/delicious-steak-with-herbs-cut-on-slices.jpg"
          alt="Image 3"
        />
        <!-- 更多图片... -->
      </div>
      <div class="prev"><</div>
      <div class="next">></div>
    </div>
  </body>
</html>
<script>
  // 获取需要的DOM元素
  const carouselImages = document.querySelector(".carousel-images");
  const images = carouselImages.querySelectorAll("img");
  const prevButton = document.querySelector(".prev");
  const nextButton = document.querySelector(".next");
  let currentImageIndex = 0;

  // 设置下一张图片的显示
  function showNextImage() {
    // 隐藏当前图片
    images[currentImageIndex].style.display = "none";

    // 更新索引并显示下一张图片(或第一张,如果当前是最后一张)
    currentImageIndex = (currentImageIndex + 1) % images.length;
    images[currentImageIndex].style.display = "block";

    console.log("设置下一张图片的显示", currentImageIndex);
  }

  // 设置上一张图片的显示
  function showPrevImage() {
    // 隐藏当前图片
    images[currentImageIndex].style.display = "none";

    // 更新索引并显示上一张图片(或最后一张,如果当前是第一张)
    currentImageIndex = (currentImageIndex - 1 + images.length) % images.length;
    images[currentImageIndex].style.display = "block";

    console.log("设置上一张图片的显示", currentImageIndex);
  }

  // 绑定点击事件
  prevButton.addEventListener("click", showPrevImage);
  nextButton.addEventListener("click", showNextImage);

  // 自动播放(可选)
  // setInterval(showNextImage, 3000); // 每3秒切换到下一张图片
</script>

 

标签:function,选项卡,05,08,js,window,var,document,display
From: https://www.cnblogs.com/iuniko/p/18181100

相关文章

  • 解决HtmlUnit执行JS报错提示ScriptException
    问题描述HtmlUnit作为一款比Selenium更轻量的HeadLess的Java版本浏览器模拟器,不需要在服务器上安装部署浏览器及其Driver程序。但是,众所周知,HtmlUnit对JS脚本的支持并不是很有话,GitHub中大部分的issue都和JS执行错误有关。笔者在实际使用(HtmlUnit4.1.0版本)过程中也遇到了JS执......
  • 20240508打卡
    第十一周第一天第二天第三天第四天第五天第六天第七天所花时间3h5h2h代码量(行)276122371博客量(篇)111知识点了解设计后台系统界面和每日委托第一阶段验收,理清项目优化方向接口测试......
  • https://github.com/long36708/long36708/blob/main/resources/img/grid-snake.svg 请
    对于这个文件,你可以将它放在你的GitHub仓库的"resources"目录下,通常也可以选择"assets"、"images"或者其他类似的名称。如果你还没有这样的目录,你可以按照以下步骤操作:在你的GitHub仓库中创建一个新的目录,可以命名为"resources"、"assets"、"images"或者其他你喜欢......
  • 08. C语言函数
    【函数基础】函数用于将程序代码分类管理,实现不同功能的代码放在不同函数内,一个函数等于一种功能,其它函数可以调用本函数执行。C语言规定所有的指令数据必须定义在函数内部,比如之前介绍的程序执行流程控制语句,另外修改全局变量的操作也是通过指令进行的,所以全局变量只能在函数内......
  • js圣杯模式
    //圣杯模式改变子属性不会影响父对应的属性//functioninherit(Target,Origin){//functionF(){}//F.prototype=Origin.prototype//Target.prototype=newF()//Target.prototype.constuctor=Target//}varinherit=......
  • JS数组常用方法
    push() -在数组末尾添加一个或多个元素,并返回新的长度。pop() -删除数组的最后一个元素,并返回那个元素。shift() -删除数组的第一个元素,并返回那个元素。unshift() -在数组的开始添加一个或多个元素,并返回新的长度。slice() -返回数组的一个浅拷......
  • ETL工具中JSON格式的转换方式
    JSON的用处JSON(JavaScript Object Notation)是一种轻量级的数据交换格式,其设计初衷是为了提升网络应用中数据的传输效率及简化数据结构的解析过程。自其诞生以来,JSON 已成为Web开发乃至众多软件开发领域中不可或缺的一部分,以其高效、灵活、易读易写的特性,成为了数据交换和存储......
  • js - try catch 应该在 for 循环里面还是外面?
    js-trycatch应该在for循环里面还是外面?使用场景因为本身trycatch放在for循环外面和里面,如果出现异常,产生的效果是不一样的。trycatch在for循环外面publicstaticvoidtryOutside(){try{for(intcount=1;count<=5;count++){......
  • Oracle 数据库执行提示:ORA-00054
    报错信息:中文:英文:ORA-00054:resourcebusyandacquirewithNOWAITspecifiedortimeoutexpired分析:资源忙,被占用了。故障处理1.检查哪个用户占用资源selectloc.session_id,obj.owner,obj.object_namefromv$locked_objectloc,dba_objectsobjwhereloc.object_id......
  • 2024-05-08:用go语言,给定一个由正整数组成的数组 nums, 找出数组中频率最高的元素, 然后
    2024-05-08:用go语言,给定一个由正整数组成的数组nums,找出数组中频率最高的元素,然后计算该元素在数组中出现的总次数。输入:nums=[1,2,2,3,1,4]。输出:4。答案2024-05-08:chatgpt题目来自leetcode3005。大体步骤如下:1.创建一个空的字典cnt用于存储每个元素的出现次数。2......