You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何将jQuery迁移至原生JavaScript?Angular.js无jQuery动态调整div大小

先来解决你Angular.js项目里的窗口resize调整div尺寸的问题,然后再聊聊jQuery转原生JS的通用方法~

针对Angular.js窗口resize指令的原生JS实现

你已经写了部分指令代码,这里帮你补全并改成纯原生JS的方式(不需要jQuery):

myApp.directive('resize', function ($window) {
  return function (scope, element) {
    const windowObj = $window;
    
    // 获取当前窗口尺寸
    scope.getWindowDimensions = function () {
      return {
        h: windowObj.innerHeight,
        w: windowObj.innerWidth
      };
    };

    // 初始化窗口尺寸
    scope.windowDimensions = scope.getWindowDimensions();

    // resize事件处理函数
    function handleResize() {
      // 手动触发Angular的digest循环,更新scope数据
      scope.$apply(function () {
        scope.windowDimensions = scope.getWindowDimensions();
        // 这里根据你的需求调整div尺寸,比如减去顶部导航栏高度
        element.css('height', `${scope.windowDimensions.h - 80}px`);
      });
    }

    // 给窗口绑定原生resize事件,加防抖避免频繁触发
    const debouncedResize = debounce(handleResize, 200);
    windowObj.addEventListener('resize', debouncedResize);

    // 指令销毁时移除事件监听,防止内存泄漏
    scope.$on('$destroy', function () {
      windowObj.removeEventListener('resize', debouncedResize);
    });

    // 简单的防抖函数
    function debounce(func, delay) {
      let timeoutId;
      return function () {
        clearTimeout(timeoutId);
        timeoutId = setTimeout(() => func.apply(this, arguments), delay);
      };
    }
  };
});

这里几个关键点:

  • 用原生的addEventListener替代jQuery的窗口resize监听,更轻量
  • 加了防抖函数,避免窗口resize时频繁触发逻辑,提升页面性能
  • 在指令销毁时移除事件监听,防止内存泄漏
  • 通过scope.$apply()触发Angular的变更检测,确保视图能及时更新

如何将jQuery代码迁移至原生JavaScript

jQuery当年是为了抹平浏览器差异而生,但现在现代浏览器的API已经很完善了,大部分操作都可以用原生JS实现,下面是常见场景的迁移方案:

1. DOM选择器

  • jQuery写法:$('.my-class')、$('#my-id')
  • 原生替代:
    • 单个元素:document.querySelector('#my-id')(返回第一个匹配的元素)
    • 多个元素:document.querySelectorAll('.my-class')(返回NodeList,可用Array.from()转成数组遍历)

2. 事件绑定与移除

  • jQuery写法:$('.btn').click(function() { /* 逻辑 */ })
  • 原生替代:
    // 单个元素绑定
    document.querySelector('.btn').addEventListener('click', handleClick);
    
    // 多个元素绑定
    Array.from(document.querySelectorAll('.btn')).forEach(btn => {
      btn.addEventListener('click', handleClick);
    });
    
    // 移除事件(必须保留handler的引用)
    element.removeEventListener('click', handleClick);
    

3. DOM样式与类操作

  • 修改样式:
    • jQuery:$('.box').css('color', 'red')
    • 原生:document.querySelector('.box').style.color = 'red'(批量样式可以用element.style.cssText)
  • 类名操作:
    • jQuery:$('.box').addClass('active')、$('.box').toggleClass('active')
    • 原生:element.classList.add('active')、element.classList.toggle('active')

4. AJAX请求

  • jQuery写法:
    $.ajax({
      url: '/api/data',
      method: 'GET',
      success: (data) => console.log(data),
      error: (err) => console.error(err)
    });
    
  • 原生替代(用fetch,现代浏览器支持):
    fetch('/api/data')
      .then(res => res.json())
      .then(data => console.log(data))
      .catch(err => console.error(err));
    

5. 遍历元素

  • jQuery写法:$('.item').each((index, el) => { /* 逻辑 */ })
  • 原生替代:
    Array.from(document.querySelectorAll('.item')).forEach((el, index) => {
      // 逻辑处理
    });
    

6. 窗口/文档尺寸获取

  • jQuery:$(window).height()、$(document).width()
  • 原生:window.innerHeight、document.documentElement.clientWidth

内容的提问来源于stack exchange,提问作者JsNinja

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.25 06:27:37