简体   繁体   English

单击另一个div中的按钮时,如何为div添加CSS样式

[英]how can i add css style for a div when i clicked on a button in another div

I'am trying to add some css styles for a div text, when I clicked a button in another div 当我单击另一个div中的按钮时,我正在尝试为div文本添加一些CSS样式

here is my html code 这是我的HTML代码

<div class="row" id="target">
  <h2>{{txt}} </h2>
</div>


<div class="row">
  <button my-dir>Click Me</button>
</div>

my js code 我的js代码

.directive('myDir', function () {
  return {
    restrict: 'A',

    link: function (scope, elem, attr) {
      console.log(elem); 
      elem.bind('click', function (e) {
        console.log("coming");
        elem.find('#target').css({
          backgroundColor: 'red'
        })    

        // angular.element(e.target).siblings('#target').addClass('clr');
      });

    }
  }
});

my problem is when I clicked on button in one div css styles has to apply for the another div using directive, I tried something like above but didn't worked. 我的问题是,当我单击一个div css样式中的按钮必须使用指令申请另一个div时,我尝试了上述类似操作,但没有成功。

Thanks in advance 提前致谢

elem will refer to the button . elem将引用该button So elem.find('#target') will look for #target inside elem 因此elem.find('#target')将在elem寻找#target

You can do like this 你可以这样

elem.bind('click', function (e) {
        $('body').find('#target').css({
          backgroundColor: 'red'
        })    
});

if your element id is unique and non changed then you can simplify it as below 如果您的元素ID是唯一且未更改,则可以如下进行简化

 elem.bind('click', function () {
         $('#target').css('backgroundColor','red');
 });

elem.find will find all div with id contains 'target', try to use unique id's for all div changes. elem.find会找到ID包含“目标”的所有div,并尝试对所有div更改使用唯一的ID。 It will help you. 它会帮助你。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 单击特定按钮时,如何使 div 缓慢滑出(使用 CSS 的转换属性)? - How can I make a div slowly slide out (with CSS' transition property) when a specific button is clicked? 单击另一个DIV时如何使DIV消失? - How do I get DIV to disappear when another DIV is clicked? 悬停父级时如何向子级 div 添加样式? - How can I add a style to a child div when hovering the parent? 仅当一个div的区域*位于另一个div下方时,如何激活css样式? 可能? - How do I activate a css style only when that area* of a div goes underneath another div? Possible? 如何使用CSS创建一个三角形div,它在单击时会消失,但在单击“溢出”部分时不会消失? - How can I create a triangle div with CSS which will disappear when clicked but not when the 'overflow' part is clicked? 单击 div 内容或 div 中的按钮时如何关闭元素? - How can I close an element when the div content or a button in the div is clicked? 当我只单击div时如何单击按钮 - How can i make a button clicked when i just click a div 我该如何做 <div> 单击按钮时滑入视图? - How Do I make a <div> slide into view when a button is clicked? </i> - How to delete the parent div when <i> tag inside button clicked? 单击按钮时如何使用 jquery 显示此 div - How do I display this div using jquery when a button is clicked
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM