イベントを介した属性値の取得・設定について書いています。それぞれ関数・メソッドに処理を記述します。記述は、サンプルコードを確認してください。
属性値の取得
getAttributeNSメソッドを使い属性値を取得する。第一引数に名前空間名、第二引数に属性名を指定する。ここでは、第一引数にnullを指定する。
図形をクリックするとコンソールに属性値を表示する。
<rect x="10" y="10" width="40" height="30" fill="cyan" onclick="showAttribute(evt)"/> <rect x="60" y="10" width="30" height="50" fill="magenta" onclick="showAttribute(evt)"/> <script type="text/javascript"> function attributeValue(evt, attname) { //属性値の取得 return `${attname}:${evt.target.getAttributeNS(null, attname)}`; } function showAttribute(evt) { console.log(attributeValue(evt, "x")); console.log(attributeValue(evt, "y")); console.log(attributeValue(evt, "width")); console.log(attributeValue(evt, "height")); console.log(attributeValue(evt, "fill")); } </script>
属性値の設定
setAttributeNSメソッドを使い属性値を設定する。第一引数に名前空間名、第二引数に属性名、第三引数に任意のデータを指定する。ここでは、第一引数にnullを指定する。
図形にマウスオーバー・マウスアウトすると塗りの色が変わる。
<ellipse cx="50" cy="35" rx="40" ry="20" fill="blue" onmouseover="setOverColor(evt)" onmouseout="setOutColor(evt)"/> <script type="text/javascript"> function setOverColor(evt) { //fill属性にcyanを設定 evt.target.setAttributeNS(null, "fill", "cyan"); } function setOutColor(evt) { //fill属性にblueを設定 evt.target.setAttributeNS(null, "fill", "blue"); } </script>
まとめ
イベントを介した属性値の取得・設定について書きました。属性値の取得にはgetAttributeNSメソッドを、属性値の設定にはsetAttributeNSメソッドを使います。