javascript - 如何用jquery设置矩形的高度和宽度

标签 javascript jquery html css svg

我正在尝试使用 jquery 设置矩形的宽度和高度,但出现错误“Uncaught TypeError: Cannot read property 'scrollWidth' of null”

以下是我的代码

$(document).ready(function() {
   var winw = $(document).width();
   var winh = $(document).height(); 

   $("#mask > rect").width(winw);
   $("#mask > rect").height(winh);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" width="0" height="0">
  <defs>
    <mask id="mask">
      <rect x="0" y="0" width="1920" height="1024" fill="#ff0000" fill-opacity=".75" />
      <circle r="140" cx="240" cy="240" fill="#000" fill-opacity="1" stroke="none" />
    </mask>
  </defs>
</svg>

最佳答案

试试attr()

$(document).ready(function() {
   var winw = $(document).width();
   var winh = $(document).height(); 
   console.log('before-width:'+$("#mask > rect").attr('width'))
   console.log('before-height:'+$("#mask > rect").attr('height'))
   $("#mask > rect").attr('width' , winw);
   $("#mask > rect").attr('height',winh);
   console.log('after-width:'+$("#mask > rect").attr('width'))
   console.log('after-height:'+$("#mask > rect").attr('height'))
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" width="0" height="0">
  <defs>
    <mask id="mask">
      <rect x="0" y="0" width="1920" height="1024" fill="#ff0000" fill-opacity=".75" />
      <circle r="140" cx="240" cy="240" fill="#000" fill-opacity="1" stroke="none" />
    </mask>
  </defs>
</svg>

关于javascript - 如何用jquery设置矩形的高度和宽度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43802099/

相关文章:

php - 用于搜索用户 token (技能)的 SQL 查询

javascript - 在 jQuery 中使用 ID 更改文本

javascript - 为什么我无法获取这个 var 的值?

javascript - 在两个 ASP.NET 页面之间传递敏感数据

asp.net - ASP.Net 应用程序的最佳菜单是什么?

jquery - 使列中的 2 个链接高度相同?

javascript - 子组件在 Angular 4 中不起作用

php - 如何在 Wordpress 中显示 HTML id 上的 slug

javascript - 查看xml是否有属性和值

javascript - 有条件地为不同的屏幕尺寸提供不同的 JavaScript