Angularjs hide and show according to screen size responsive

情到浓时终转凉″ 提交于 2019-12-11 01:54:27

问题


Hi every one I am trying to achieve this

When the user is on desktop, he should see the block when he visits the page, and the user should see the button when he is on mobile and then he should be able to toggle it.

I am able to show the button using CSS media query by setting display: none when screen size is <480px and also able to revert the display: none to block by adding ng-click="showBlocks={'display': 'block'}

But I am not sure how can i make it work in a sense when I click on it again it should hide the blocks again.

I have tried ng-hide/show but it doesn't work unless i remove display:none for the mobile size and when i do remove it then I am not able to see the blocks when visit the page for first time.

Please help me I have wasted so much time on it. Thanks in advance


回答1:


Without a code sample it's hard to tell where you are. If you managed to get the button to hide the blocks (like you said with ng-click="showBlocks={'display': 'block'}) then adding a variable should be enough. Add this to the button element:

ng-init="show=true;" ng-click="show = !show; showBlocks={'display': (show?'block':'none')};"

If that works, then move the initialisation logic to the controller to keep things clean.




回答2:


You can add a class on that element which you want to force show if user clicks on the button and use the !important flag in the CSS or simply define that rule below the media query to give the higher preference to that CSS class.

Suppose you are adding force-show class when user toggles it:

.force-show {
    display: block !important
}

See an example below. Use the "Full Page" link to mock the desktop view in the below example

var app = angular.module("sa", []);

app.controller("FooController", function($scope) {

});
.block {
  height: 100px;
  background: #ddd;
}
button {
  display: none
}
@media (max-width: 767px) {
  .block {
    display: none;
  }
  button {
    display: block;
  }
}
.force-show {
  display: block;
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>

<div ng-app="sa" ng-controller="FooController">
  <div class="block" ng-class="{'force-show': showBlock}">
    I'll only be visible on desktop or using button on mobile.
  </div>

  <button ng-click="showBlock = !showBlock">Toggle blocks
  </button>
</div>


来源:https://stackoverflow.com/questions/38919796/angularjs-hide-and-show-according-to-screen-size-responsive

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!