大网数据广告活动
Web 标准与前端开发

SVGRectElement

· 52CE 我爱测

The `SVGRectElement` interface provides access to the properties of rect elements, as well as methods to manipulate them.

SVG

The SVGRectElement interface provides access to the properties of rect elements, as well as methods to manipulate them.

Instance properties

This interface also inherits properties from its parent, SVGGeometryElement.

  • SVGRectElement.x
    • : Returns an SVGAnimatedLength corresponding to the x attribute of the given rect element.
  • SVGRectElement.y
    • : Returns an SVGAnimatedLength corresponding to the y attribute of the given rect element.
  • SVGRectElement.width
    • : Returns an SVGAnimatedLength corresponding to the width attribute of the given rect element.
  • SVGRectElement.height
    • : Returns an SVGAnimatedLength corresponding to the height attribute of the given rect element.
  • SVGRectElement.rx
    • : Returns an SVGAnimatedLength corresponding to the rx attribute of the given rect element.
  • SVGRectElement.ry
    • : Returns an SVGAnimatedLength corresponding to the ry attribute of the given rect element.

Instance methods

This interface doesn't implement any specific methods, but inherits methods from its parent, SVGGeometryElement.

Examples

Changing the color of an SVG rectangle

This example sets the fill color of an SVGRectElement to a random value whenever the user clicks it.

HTML

<svg xmlns="http://www.w3.org/2000/svg" version="1.1">
  <rect width="300" height="100" id="myrect" />
  <text x="60" y="40" fill="white" font-size="40">Click Me</text>
</svg>

CSS

#myrect {
  fill: blue;
  stroke-width: 1;
  stroke: black;
}

JavaScript

const myRect = document.querySelector("#myrect");

myRect.addEventListener("click", () => {
  const r = Math.floor(Math.random() * 255);
  const g = Math.floor(Math.random() * 255);
  const b = Math.floor(Math.random() * 255);
  myRect.style.fill = `rgb(${r} ${g} ${b})`;
});

Result

Changing the color of an SVG rectangle

Specifications

Browser compatibility

See also

  • rect

来源:MDN Web Docs / Mozilla 贡献者 · 作者与贡献记录 · CC BY-SA 2.5。离线整理了版式、链接和媒体显示。

资料来源与适用范围

资料来源
MDN Web Docs / Mozilla 贡献者
适用范围
请按文中版本与环境说明核对
内容语言
中文;命令、路径和错误标识保留技术原文
本地收录日期
2026-11-15
授权说明
CC BY-SA 2.5

正文与所需资源由本站本地存储。查看来源及更新记录 ↗

请按适用版本和实际日志确认原因;本站没有对每一种系统或设备逐项执行文中的操作。